MLIR 24.0.0git
NVGPUTransformOps.cpp
Go to the documentation of this file.
1//===- NVGPUTransformOps.cpp - Implementation of NVGPU transform ops ------===//
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
30#include "mlir/IR/AffineExpr.h"
32#include "mlir/IR/Value.h"
33#include "llvm/ADT/ArrayRef.h"
34
35using namespace mlir;
36using namespace mlir::linalg;
37using namespace mlir::nvgpu;
38using namespace mlir::NVVM;
39using namespace mlir::transform;
40
41#define DEBUG_TYPE "nvgpu-transforms"
42
43//===----------------------------------------------------------------------===//
44// Apply...ConversionPatternsOp
45//===----------------------------------------------------------------------===//
46
47void ApplyNVGPUToNVVMConversionPatternsOp::populatePatterns(
48 TypeConverter &typeConverter, RewritePatternSet &patterns) {
49 auto &llvmTypeConverter = static_cast<LLVMTypeConverter &>(typeConverter);
50 /// device-side async tokens cannot be materialized in nvvm. We just
51 /// convert them to a dummy i32 type in order to easily drop them during
52 /// conversion.
54 llvmTypeConverter.addConversion([&](DeviceAsyncTokenType type) -> Type {
55 return llvmTypeConverter.convertType(
56 IntegerType::get(type.getContext(), 32));
57 });
58 llvmTypeConverter.addConversion([&](MBarrierTokenType type) -> Type {
59 return llvmTypeConverter.convertType(
60 IntegerType::get(type.getContext(), 64));
61 });
62 llvmTypeConverter.addConversion([&](WarpgroupAccumulatorType type) -> Type {
63 Type elemType = type.getFragmented().getElementType();
64 int64_t sizeM = type.getFragmented().getDimSize(0);
65 int64_t sizeN = type.getFragmented().getDimSize(1);
66
67 unsigned numMembers;
68 if (elemType.isF32() || elemType.isInteger(32))
69 numMembers = sizeN / 2;
70 else if (elemType.isF16())
71 numMembers = sizeN / 4;
72 else
73 llvm_unreachable("unsupported type for warpgroup accumulator");
74
75 SmallVector<Type> innerStructBody;
76 for (unsigned i = 0; i < numMembers; i++)
77 innerStructBody.push_back(elemType);
78 auto innerStructType =
79 LLVM::LLVMStructType::getLiteral(type.getContext(), innerStructBody);
80
81 SmallVector<Type> structBody;
82 for (int i = 0; i < sizeM; i += kWgmmaSizeM)
83 structBody.push_back(innerStructType);
84
85 auto convertedType =
86 LLVM::LLVMStructType::getLiteral(type.getContext(), structBody);
87 return llvmTypeConverter.convertType(convertedType);
88 });
89 llvmTypeConverter.addConversion([&](MBarrierGroupType type) -> Type {
90 return llvmTypeConverter.convertType(
91 getMBarrierMemrefType(type.getContext(), type));
92 });
93 llvmTypeConverter.addConversion(
94 [&](WarpgroupMatrixDescriptorType type) -> Type {
95 return llvmTypeConverter.convertType(
96 IntegerType::get(type.getContext(), 64));
97 });
98 llvmTypeConverter.addConversion([&](TensorMapDescriptorType type) -> Type {
99 return LLVM::LLVMPointerType::get(type.getContext());
100 });
101 populateNVGPUToNVVMConversionPatterns(llvmTypeConverter, patterns);
102}
103
104LogicalResult ApplyNVGPUToNVVMConversionPatternsOp::verifyTypeConverter(
105 TypeConverterBuilderOpInterface builder) {
106 if (builder.getTypeConverterType() != "LLVMTypeConverter")
107 return emitOpError("expected LLVMTypeConverter");
108 return success();
109}
110
111//===---------------------------------------------------------------------===//
112// CreateAsyncGroupsOp
113//===---------------------------------------------------------------------===//
114
115void CreateAsyncGroupsOp::getEffects(
117 consumesHandle(getTargetMutable(), effects);
118 producesHandle(getOperation()->getOpResults(), effects);
119 modifiesPayload(effects);
120}
121
123CreateAsyncGroupsOp::applyToOne(TransformRewriter &rewriter, Operation *target,
124 ApplyToEachResultList &results,
125 TransformState &state) {
126 createAsyncGroups(rewriter, target, getBypassL1());
127 results.push_back(target);
129}
130
131//===----------------------------------------------------------------------===//
132// PipelineSharedMemoryCopiesOp
133//===----------------------------------------------------------------------===//
134
135/// Returns true if the given type has the default memory space.
137 return !type.getMemorySpace() || type.getMemorySpaceAsInt() == 0;
138}
139
140/// Returns true if the given type has the shared (workgroup) memory space.
142 auto space =
143 dyn_cast_if_present<gpu::AddressSpaceAttr>(type.getMemorySpace());
144 return space &&
145 space.getValue() == gpu::GPUDialect::getWorkgroupAddressSpace();
146}
147
148/// Returns the value produced by a load from the default memory space. Returns
149/// null if the operation is not such a load.
151 // TODO: consider an interface or leveraging the memory effects interface.
152 auto load = dyn_cast<vector::TransferReadOp>(op);
153 if (!load)
154 return nullptr;
155
156 auto loadType = dyn_cast<MemRefType>(load.getBase().getType());
157 if (!loadType || !hasDefaultMemorySpace(loadType))
158 return nullptr;
159 return load;
160}
161
162/// Returns true if the operation is storing the given value into shared memory.
163static bool isStoreToShared(Operation *op, Value v) {
164 // TOD: consider an interface or leveraging the memory effects interface.
165 auto store = dyn_cast<vector::TransferWriteOp>(op);
166 if (!store || store.getVector() != v)
167 return false;
168
169 auto storeType = dyn_cast<MemRefType>(store.getBase().getType());
170 return storeType || hasSharedMemorySpace(storeType);
171}
172
173/// Returns true if the operation is a load from the default memory space the
174/// result of which is only stored into the shared memory space.
176 Value loaded = getValueLoadedFromGlobal(op);
177 if (!loaded || !loaded.hasOneUse())
178 return false;
179
180 return isStoreToShared(*loaded.getUsers().begin(), loaded);
181}
182
183/// Populate `ops` with the set of operations that belong to the stage 0 of the
184/// pipelined version of the given loop when pipelining copies to shared memory.
185/// Specifically, this collects:
186///
187/// 1. all loads from global memory, both sync and async;
188/// 2. the barriers for async loads.
189///
190/// In particular, barriers are omitted if they do not dominate at least one
191/// async load for which there is not yet a barrier.
192static LogicalResult
195
197 for (Operation &op : *forOp.getBody()) {
198 // Bail on nested ops for now.
199 if (op.getNumRegions() > 0)
200 return failure();
201
202 if (isa<gpu::BarrierOp>(op)) {
203 barriers.insert(&op);
204 continue;
205 }
206
207 if (isa<DeviceAsyncCopyOp, DeviceAsyncCreateGroupOp>(op)) {
208 ops.insert(&op);
209 ops.insert(std::make_move_iterator(barriers.begin()),
210 std::make_move_iterator(barriers.end()));
211 assert(barriers.empty() &&
212 "expected to have moved the barriers into another set");
213 continue;
214 }
215
217 ops.insert(&op);
218 continue;
219 }
220 }
221
222 return success();
223}
224
225/// Hook for the loop pipeliner that sets the "num groups in flight" attribute
226/// of async wait operations corresponding to pipelined shared memory copies.
227// TODO: this currently assumes that there are no groups that could be in flight
228// in the existing code.
229static void
232 unsigned iteration, unsigned depth) {
233 // Based on the order of copies within the loop we need to set the number
234 // of copies in flight, unless it is already set.
235 auto waitOp = dyn_cast<DeviceAsyncWaitOp>(op);
236 if (!waitOp || waitOp.getNumGroups())
237 return;
238
239 int numGroupInFlight = 0;
242 numGroupInFlight = depth - 1;
243 } else {
244 // By construction there should be no wait op in the prologue as all the
245 // wait should be in the last stage.
247 // Based on the schedule we pick we know how many groups are in flight for
248 // each iteration of the epilogue.
249 numGroupInFlight = depth - 1 - iteration;
250 }
251 waitOp.setNumGroups(numGroupInFlight);
252}
253
254/// Hook for the loop pipeliner that populates `ops` with the stage information
255/// as follows:
256///
257/// - operations in `stage0Ops` (typically loads from global memory and
258/// related barriers) are at stage 0;
259/// - operations in the backward slice of any stage0Ops are all at stage 0;
260/// - other operations are at stage `depth`;
261/// - the internal order of the pipelined loop has ops at stage `depth` first,
262/// then those at stage 0, with relative order within each group preserved.
263///
265 scf::ForOp forOp,
266 std::vector<std::pair<Operation *, unsigned>> &opsWithPipelineStages,
267 unsigned depth, llvm::SmallPtrSetImpl<Operation *> &stage0Ops) {
268 SetVector<Operation *> dependencies;
270 return visited->getBlock() == forOp.getBody();
271 });
272 options.inclusive = true;
273 for (Operation &op : forOp.getBody()->getOperations()) {
274 if (stage0Ops.contains(&op)) {
275 LogicalResult result = getBackwardSlice(&op, &dependencies, options);
276 assert(result.succeeded() && "expected a backward slice");
277 (void)result;
278 }
279 }
280
281 for (Operation &op : forOp.getBody()->getOperations()) {
282 if (!dependencies.contains(&op) && !isa<scf::YieldOp>(op))
283 opsWithPipelineStages.emplace_back(&op, depth);
284 }
285 for (Operation &op : forOp.getBody()->getOperations()) {
286 if (dependencies.contains(&op))
287 opsWithPipelineStages.emplace_back(&op, 0);
288 }
289}
290
291/// Hook for the loop pipeliner. Replaces op with a predicated version and
292/// returns the resulting operation. Returns the original op if the predication
293/// isn't necessary for the given op. Returns null if predication is needed but
294/// not supported.
296 Operation *op, Value predicate) {
297 // Some operations may be fine to execute "speculatively" more times than the
298 // original number of iterations, in particular side-effect free operations
299 // and barriers, even if they cannot be predicated.
300 if (isMemoryEffectFree(op) ||
301 isa<gpu::BarrierOp, DeviceAsyncCreateGroupOp, DeviceAsyncWaitOp>(op)) {
302 return op;
303 }
304
305 // Otherwise, only async copies can currently be predicated.
306 auto asyncCopyOp = dyn_cast<DeviceAsyncCopyOp>(op);
307 if (!asyncCopyOp)
308 return nullptr;
309
310 // Create srcElement Value based on `predicate`. The next lines generate
311 // the following code:
312 //
313 // srcElement = (pred) ? prevSrcElements : 0;
314 //
315 Location loc = asyncCopyOp->getLoc();
316 Value dstElements = arith::ConstantOp::create(
317 rewriter, loc, asyncCopyOp.getDstElementsAttr());
318 Value originalSrcElement =
319 asyncCopyOp.getSrcElements() ? asyncCopyOp.getSrcElements() : dstElements;
320 Value c0Index = arith::ConstantIndexOp::create(rewriter, loc, 0);
321 auto srcElements = arith::SelectOp::create(rewriter, loc, predicate,
322 originalSrcElement, c0Index);
323 auto asyncCopyZeroFillOp = DeviceAsyncCopyOp::create(
324 rewriter, loc, DeviceAsyncTokenType::get(asyncCopyOp.getContext()),
325 asyncCopyOp.getDst(), asyncCopyOp.getDstIndices(), asyncCopyOp.getSrc(),
326 asyncCopyOp.getSrcIndices(), asyncCopyOp.getDstElements(), srcElements,
327 UnitAttr());
328 rewriter.replaceOp(asyncCopyOp, asyncCopyZeroFillOp);
329 return asyncCopyZeroFillOp;
330}
331
332/// Applies loop pipelining with the given depth to the given loop so that
333/// copies into the shared memory are pipelined. Doesn't affect other loops.
334/// Returns a pair containing the error state and the pipelined op, the latter
335/// being null in case of any failure. The error state contains a definite error
336/// if the IR has been modified and a silenceable error otherwise.
337static std::tuple<DiagnosedSilenceableFailure, scf::ForOp>
338pipelineForSharedCopies(RewriterBase &rewriter, scf::ForOp forOp, int64_t depth,
339 bool epiloguePeeling) {
341 if (failed(collectStage0PipeliningOps(forOp, stage0Ops))) {
342 return std::make_tuple(
343 emitSilenceableFailure(forOp, "cannot find stage 0 ops for pipelining"),
344 scf::ForOp());
345 }
346 if (stage0Ops.empty()) {
347 return std::make_tuple(
348 emitSilenceableFailure(forOp, "no shared memory copy"), scf::ForOp());
349 }
350
352 unsigned maxDepth = depth;
353 auto setAnnotation = [&](Operation *op,
355 unsigned iteration) {
356 return setAsyncWaitGroupsInFlight(rewriter, op, part, iteration, maxDepth);
357 };
358 options.getScheduleFn =
359 [&](scf::ForOp schedulingFor,
360 std::vector<std::pair<Operation *, unsigned>> &ops) {
361 if (schedulingFor != forOp)
362 return;
363 return getPipelineStages(forOp, ops, maxDepth, stage0Ops);
364 };
365 options.annotateFn = setAnnotation;
366 if (!epiloguePeeling) {
367 options.peelEpilogue = false;
369 }
370
371 OpBuilder::InsertionGuard guard(rewriter);
372 rewriter.setInsertionPoint(forOp);
373 bool modifiedIR;
374 FailureOr<scf::ForOp> maybePipelined =
375 pipelineForLoop(rewriter, forOp, options, &modifiedIR);
376 if (succeeded(maybePipelined)) {
377 return std::make_tuple(DiagnosedSilenceableFailure::success(),
378 *maybePipelined);
379 }
380 return std::make_tuple(
381 modifiedIR
383 : emitSilenceableFailure(forOp, "pipelining preconditions failed"),
384 scf::ForOp());
385}
386
387DiagnosedSilenceableFailure PipelineSharedMemoryCopiesOp::applyToOne(
388 TransformRewriter &rewriter, scf::ForOp forOp,
389 ApplyToEachResultList &results, TransformState &state) {
390 auto [diag, pipelined] = pipelineForSharedCopies(
391 rewriter, forOp, static_cast<int64_t>(getDepth()), getPeelEpilogue());
392 if (diag.succeeded()) {
393 results.push_back(pipelined);
395 }
396 if (diag.isDefiniteFailure()) {
397 auto diag = emitDefiniteFailure("irreversible pipelining failure");
398 if (!getPeelEpilogue()) {
399 diag.attachNote(forOp->getLoc()) << "couldn't predicate?";
400 diag.attachNote(getLoc()) << "try setting " << getPeelEpilogueAttrName();
401 }
402 return diag;
403 }
404
405 return std::move(diag);
406}
407
408//===----------------------------------------------------------------------===//
409// RewriteMatmulAsMmaSyncOp
410//===----------------------------------------------------------------------===//
411
412/// Helper struct to encode a pair of row/column indexings in the form of
413/// affine expressions.
414struct RowColIndexing : private std::pair<AffineExpr, AffineExpr> {
417
418 AffineExpr row() const { return first; };
419 AffineExpr col() const { return second; };
420
421 void print(llvm::raw_ostream &os) const {
422 os << "- indexing: " << first << ", " << second;
423 }
424};
425
426/// Helper struct to provide a simple mapping from matmul operations to the
427/// corresponding mma.sync operation. This is constrained to the case where the
428/// matmul matches the mma.sync operation 1-1.
431 : b(b), loc(loc), laneId(laneId) {}
432
434 std::function<SmallVector<RowColIndexing>(MLIRContext *)>;
435
436 /// Create the mma.sync operation corresponding to `linalgOp` along with all
437 /// the supporting load/store and vector operations.
438 FailureOr<Operation *> buildMmaSync(LinalgOp linalgOp);
439
440private:
441 struct MmaSyncInfo {
442 std::tuple<IndexCalculator, IndexCalculator, IndexCalculator> indexFns;
443 std::tuple<SmallVector<int64_t>, SmallVector<int64_t>, SmallVector<int64_t>>
444 vectorShapes;
445 SmallVector<int64_t> mmaShape;
446 bool tf32Enabled;
447 };
448
449 /// Return the specific index calculator for the given `linalgOp` or failure
450 /// if the op is not supported. This is the toplevel switch that should just
451 /// be Tablegen'd in the future.
452 FailureOr<MmaSyncInfo> getIndexCalculators(ArrayRef<int64_t> opShape,
453 TypeRange elementalTypes);
454
455 //===--------------------------------------------------------------------===//
456 // Instruction-specific row, column indexing expression builders.
457 // These should all be declaratively specified via Tablegen in the future.
458 // The Tablegen specification should be as straightforward as possible to
459 // only model the existing size and type combinations.
460 //===--------------------------------------------------------------------===//
461 //
462 // TODO: Tablegen all this.
463 //===--------------------------------------------------------------------===//
464 // m16n8k4 tf32 case.
465 //===--------------------------------------------------------------------===//
466 /// From the NVIDIA doc:
467 /// groupID = %laneid >> 2
468 /// threadIDInGroup = %laneid % 4
469 /// row = groupID for a0
470 /// groupID + 8 for a1
471 /// col = threadIDInGroup
472 static SmallVector<RowColIndexing> m16n8k4tf32Lhs(MLIRContext *ctx) {
473 auto dim = getAffineDimExpr(0, ctx);
474 AffineExpr groupID = dim.floorDiv(4);
475 AffineExpr threadIDInGroup = dim % 4;
476 return {RowColIndexing{groupID, threadIDInGroup},
477 RowColIndexing{groupID + 8, threadIDInGroup}};
478 }
479
480 /// From the NVIDIA doc:
481 /// groupID = %laneid >> 2
482 /// threadIDInGroup = %laneid % 4
483 /// row = threadIDInGroup
484 /// col = groupID
485 static SmallVector<RowColIndexing> m16n8k4tf32Rhs(MLIRContext *ctx) {
486 auto dim = getAffineDimExpr(0, ctx);
487 AffineExpr groupID = dim.floorDiv(4);
488 AffineExpr threadIDInGroup = dim % 4;
489 return {RowColIndexing{threadIDInGroup, groupID}};
490 }
491
492 /// From the NVIDIA doc:
493 /// groupID = %laneid >> 2
494 /// threadIDInGroup = %laneid % 4
495 /// row = groupID for c0 and c1
496 /// groupID + 8 for c2 and c3
497 /// col = (threadIDInGroup * 2) + (i & 0x1) for ci where i = {0,..,3}
498 static SmallVector<RowColIndexing> m16n8k4tf32Res(MLIRContext *ctx) {
499 auto dim = getAffineDimExpr(0, ctx);
500 AffineExpr groupID = dim.floorDiv(4);
501 AffineExpr threadIDInGroup = dim % 4;
502 return {RowColIndexing{groupID, threadIDInGroup * 2 + 0},
503 RowColIndexing{groupID, threadIDInGroup * 2 + 1},
504 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 0},
505 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 1}};
506 }
507
508 //===--------------------------------------------------------------------===//
509 // m16n8k16 f16 case.
510 //===--------------------------------------------------------------------===//
511 /// From the NVIDIA doc:
512 /// groupID = %laneid >> 2
513 /// threadIDInGroup = %laneid % 4
514 ///
515 /// row = groupID for ai where 0 <= i < 2 || 4 <= i < 6
516 /// groupID + 8 Otherwise
517 ///
518 /// col = (threadIDInGroup * 2) + (i & 0x1) for ai where i < 4
519 /// (threadIDInGroup * 2) + (i & 0x1) + 8 for ai where i >= 4
520 static SmallVector<RowColIndexing> m16n8k16f16Lhs(MLIRContext *ctx) {
521 auto dim = getAffineDimExpr(0, ctx);
522 AffineExpr groupID = dim.floorDiv(4);
523 AffineExpr threadIDInGroup = dim % 4;
524 // clang-format off
525 return {
526 RowColIndexing{groupID, threadIDInGroup * 2 + 0}, // i == 0
527 RowColIndexing{groupID, threadIDInGroup * 2 + 1}, // i == 1
528 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 0}, // i == 2
529 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 1}, // i == 3
530 RowColIndexing{groupID, threadIDInGroup * 2 + 0 + 8}, // i == 4
531 RowColIndexing{groupID, threadIDInGroup * 2 + 1 + 8}, // i == 5
532 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 0 + 8}, // i == 6
533 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 1 + 8} // i == 7
534 };
535 // clang-format on
536 }
537
538 /// From the NVIDIA doc:
539 /// groupID = %laneid >> 2
540 /// threadIDInGroup = %laneid % 4
541 ///
542 /// row = (threadIDInGroup * 2) + (i & 0x1) for bi where i < 2
543 /// (threadIDInGroup * 2) + (i & 0x1) + 8 for bi where i >= 2
544 ///
545 /// col = groupID
546 static SmallVector<RowColIndexing> m16n8k16f16Rhs(MLIRContext *ctx) {
547 auto dim = getAffineDimExpr(0, ctx);
548 AffineExpr groupID = dim.floorDiv(4);
549 AffineExpr threadIDInGroup = dim % 4;
550 // clang-format off
551 return {
552 RowColIndexing{threadIDInGroup * 2 + 0, groupID}, // i == 0
553 RowColIndexing{threadIDInGroup * 2 + 1, groupID}, // i == 1
554 RowColIndexing{threadIDInGroup * 2 + 0 + 8, groupID}, // i == 2
555 RowColIndexing{threadIDInGroup * 2 + 1 + 8, groupID} // i == 3
556 };
557 // clang-format on
558 }
559
560 /// From the NVIDIA doc:
561 /// groupID = %laneid >> 2
562 /// threadIDInGroup = %laneid % 4
563 ///
564 /// row = groupID for ci where i < 2
565 /// groupID + 8 for ci where i >= 2
566 ///
567 /// col = (threadIDInGroup * 2) + (i & 0x1) for ci where i = {0,..,3}
568 static SmallVector<RowColIndexing> m16n8k16f16Res(MLIRContext *ctx) {
569 auto dim = getAffineDimExpr(0, ctx);
570 AffineExpr groupID = dim.floorDiv(4);
571 AffineExpr threadIDInGroup = dim % 4;
572 // clang-format off
573 return {
574 RowColIndexing{groupID, threadIDInGroup * 2 + 0}, // i == 0
575 RowColIndexing{groupID, threadIDInGroup * 2 + 1}, // i == 1
576 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 0}, // i == 2
577 RowColIndexing{groupID + 8, threadIDInGroup * 2 + 1} // i == 3
578 };
579 // clang-format on
580 }
581
582 //===--------------------------------------------------------------------===//
583 /// Helper functions to create customizable load and stores operations. The
584 /// specific shapes of each MMA instruction are passed via the
585 /// IndexCalculator callback.
586 //===--------------------------------------------------------------------===//
587 /// Build a list of memref.load operations indexed at `(row, col)` indices
588 /// that make sense for a particular MMA instruction and specified via the
589 /// IndexCalculator callback.
590 SmallVector<Value> buildMemRefLoads(OpBuilder &b, Location loc,
591 OpFoldResult laneId, Value memref,
592 const IndexCalculator &indexFn);
593
594 /// Perform a distributed load of a vector operand of `vectorShape` for a
595 /// particular MMA instruction whose `(row, col)` indices are specified via
596 /// the IndexCalculator callback. Each `laneId` loads the subportion of the
597 /// data that makes sense for the particular MMA operation.
598 /// The `vectorShape` matches existing NVGPU dialect op specification but
599 /// could also be flattened in the future if needed for simplification.
600 Value buildMmaSyncMemRefLoadOperand(OpBuilder &b, Location loc,
601 OpFoldResult laneId, Value memref,
602 IndexCalculator indexFn,
603 ArrayRef<int64_t> vectorShape);
604
605 /// Build a list of memref.store operations indexed at `(row, col)` indices
606 /// that make sense for a particular MMA instruction and specified via the
607 /// IndexCalculator callback.
608 SmallVector<Operation *> buildMemRefStores(OpBuilder &b, Location loc,
609 ValueRange toStore,
610 OpFoldResult laneId, Value memref,
611 const IndexCalculator &indexFn);
612
613 /// Perform a distributed store of a vector operand of `vectorShape` for a
614 /// particular MMA instruction whose `(row, col)` indices are specified via
615 /// the IndexCalculator callback. Each `laneId` loads the subportion of the
616 /// data that makes sense for the particular MMA operation.
617 /// The `vectorShape` matches existing NVGPU dialect op specification but
618 /// could also be flattened in the future if needed for simplification.
619 SmallVector<Operation *> buildMmaSyncMemRefStoreOperand(
620 OpBuilder &b, Location loc, Value vectorToStore, OpFoldResult laneId,
621 Value memref, IndexCalculator indexFn, ArrayRef<int64_t> vectorShape);
622
623 OpBuilder &b;
624 Location loc;
625 OpFoldResult laneId;
626};
627
628//===--------------------------------------------------------------------===//
629/// Helper functions to create customizable load and stores operations. The
630/// specific shapes of each MMA instruction are passed via the
631/// IndexCalculator callback.
632//===--------------------------------------------------------------------===//
633
634template <typename ApplyFn, typename ReduceFn>
635static void foreachIndividualVectorElement(Value vector, ApplyFn applyFn,
636 ReduceFn reduceFn) {
637 VectorType vectorType = cast<VectorType>(vector.getType());
638 auto vectorShape = vectorType.getShape();
639 auto strides = computeStrides(vectorShape);
640 for (int64_t idx = 0, e = vectorShape[0] * strides[0]; idx < e; ++idx) {
641 auto indices = delinearize(idx, strides);
642 reduceFn(applyFn(vector, idx, indices), idx, indices);
643 }
644}
645
647MmaSyncBuilder::buildMemRefLoads(OpBuilder &b, Location loc,
648 OpFoldResult laneId, Value memref,
649 const IndexCalculator &indexFn) {
650 auto aff = [&](AffineExpr e) {
651 return affine::makeComposedFoldedAffineApply(b, loc, e, laneId);
652 };
653 SmallVector<Value> res;
654 SmallVector<RowColIndexing> indexings = indexFn(b.getContext());
655 for (auto indexing : indexings) {
656 Value row = getValueOrCreateConstantIndexOp(b, loc, aff(indexing.row()));
657 Value col = getValueOrCreateConstantIndexOp(b, loc, aff(indexing.col()));
658 auto load = memref::LoadOp::create(b, loc, memref, ValueRange{row, col});
659 res.push_back(load);
660 }
661 return res;
662}
663
664Value MmaSyncBuilder::buildMmaSyncMemRefLoadOperand(
666 IndexCalculator indexFn, ArrayRef<int64_t> vectorShape) {
667 auto loads = buildMemRefLoads(b, loc, laneId, memref, indexFn);
668
669 Type elementType = getElementTypeOrSelf(memref.getType());
670 auto vt = VectorType::get(vectorShape, elementType);
671 Value res = vector::BroadcastOp::create(b, loc, vt, loads[0]);
673 res,
674 /*applyFn=*/
675 [&](Value v, int64_t linearIdx, ArrayRef<int64_t> indices) {
676 return loads[linearIdx];
677 },
678 /*reduceFn=*/
679 [&](Value v, int64_t linearIdx, ArrayRef<int64_t> indices) {
680 res = vector::InsertOp::create(b, loc, v, res, indices);
681 });
682
683 return res;
684}
685
686SmallVector<Operation *> MmaSyncBuilder::buildMemRefStores(
687 OpBuilder &b, Location loc, ValueRange toStore, OpFoldResult laneId,
688 Value memref, const IndexCalculator &indexFn) {
689 auto aff = [&](AffineExpr e) {
690 return affine::makeComposedFoldedAffineApply(b, loc, e, laneId);
691 };
692 SmallVector<Operation *> res;
693 for (auto [indexing, val] :
694 llvm::zip_equal(indexFn(b.getContext()), toStore)) {
695 Value row = getValueOrCreateConstantIndexOp(b, loc, aff(indexing.row()));
696 Value col = getValueOrCreateConstantIndexOp(b, loc, aff(indexing.col()));
697 Operation *store =
698 memref::StoreOp::create(b, loc, val, memref, ValueRange{row, col});
699 res.push_back(store);
700 }
701 return res;
702}
703
704SmallVector<Operation *> MmaSyncBuilder::buildMmaSyncMemRefStoreOperand(
705 OpBuilder &b, Location loc, Value vectorToStore, OpFoldResult laneId,
706 Value memref, IndexCalculator indexFn, ArrayRef<int64_t> vectorShape) {
707 SmallVector<Value> toStore;
708 toStore.reserve(32);
710 vectorToStore,
711 /*applyFn=*/
712 [&](Value v, int64_t linearIdx, ArrayRef<int64_t> indices) {
713 return vector::ExtractOp::create(b, loc, vectorToStore, indices);
714 },
715 /*reduceFn=*/
716 [&](Value v, int64_t linearIdx, ArrayRef<int64_t> indices) {
717 toStore.push_back(v);
718 });
719 return buildMemRefStores(b, loc, toStore, laneId, memref, indexFn);
720}
721
722static std::tuple<SmallVector<int64_t>, SmallVector<int64_t>,
725 ArrayRef<int64_t> res) {
726 SmallVector<int64_t> vlhs(lhs);
727 SmallVector<int64_t> vrhs(rhs);
728 SmallVector<int64_t> vres(res);
729 return std::make_tuple(vlhs, vrhs, vres);
730}
731
732FailureOr<MmaSyncBuilder::MmaSyncInfo>
733MmaSyncBuilder::getIndexCalculators(ArrayRef<int64_t> opShape,
734 TypeRange elementalTypes) {
735 // TODO: Tablegen all this.
736 Type f16 = b.getF16Type();
737 Type f32 = b.getF32Type();
738 if (opShape == ArrayRef<int64_t>{16, 8, 4} &&
739 elementalTypes == TypeRange{f32, f32, f32}) {
740 return MmaSyncInfo{std::make_tuple(&MmaSyncBuilder::m16n8k4tf32Lhs,
741 &MmaSyncBuilder::m16n8k4tf32Rhs,
742 &MmaSyncBuilder::m16n8k4tf32Res),
743 makeVectorShapes({2, 1}, {1, 1}, {2, 2}),
744 SmallVector<int64_t>{opShape},
745 /*tf32Enabled=*/true};
746 }
747 // This is the version with f16 accumulation.
748 // TODO: version with f32 accumulation.
749 if (opShape == ArrayRef<int64_t>{16, 8, 16} &&
750 elementalTypes == TypeRange{f16, f16, f16}) {
751 return MmaSyncInfo{std::make_tuple(&MmaSyncBuilder::m16n8k16f16Lhs,
752 &MmaSyncBuilder::m16n8k16f16Rhs,
753 &MmaSyncBuilder::m16n8k16f16Res),
754 makeVectorShapes({4, 2}, {2, 2}, {2, 2}),
755 SmallVector<int64_t>{opShape},
756 /*tf32Enabled=*/false};
757 }
758 return failure();
759}
760
761FailureOr<Operation *> MmaSyncBuilder::buildMmaSync(LinalgOp linalgOp) {
762 Value lhsMemRef = linalgOp.getDpsInputOperand(0)->get();
763 Value rhsMemRef = linalgOp.getDpsInputOperand(1)->get();
764 Value resMemRef = linalgOp.getDpsInitOperand(0)->get();
765 assert(cast<MemRefType>(lhsMemRef.getType()).getRank() == 2 &&
766 "expected lhs to be a 2D memref");
767 assert(cast<MemRefType>(rhsMemRef.getType()).getRank() == 2 &&
768 "expected rhs to be a 2D memref");
769 assert(cast<MemRefType>(resMemRef.getType()).getRank() == 2 &&
770 "expected res to be a 2D memref");
771
772 int64_t m = cast<MemRefType>(lhsMemRef.getType()).getShape()[0];
773 int64_t n = cast<MemRefType>(rhsMemRef.getType()).getShape()[1];
774 int64_t k = cast<MemRefType>(lhsMemRef.getType()).getShape()[1];
775 Type lhsType = getElementTypeOrSelf(lhsMemRef.getType());
776 Type rhsType = getElementTypeOrSelf(rhsMemRef.getType());
777 Type resType = getElementTypeOrSelf(resMemRef.getType());
778
779 FailureOr<MmaSyncInfo> maybeInfo =
780 getIndexCalculators({m, n, k}, {lhsType, rhsType, resType});
781 if (failed(maybeInfo))
782 return failure();
783
784 const MmaSyncInfo &info = *maybeInfo;
785 auto [lhsIndexFn, rhsIndexFn, resIndexFn] = info.indexFns;
786 auto [lhsShape, rhsShape, resShape] = info.vectorShapes;
787 Value lhs = buildMmaSyncMemRefLoadOperand(b, loc, laneId, lhsMemRef,
788 lhsIndexFn, lhsShape);
789 Value rhs = buildMmaSyncMemRefLoadOperand(b, loc, laneId, rhsMemRef,
790 rhsIndexFn, rhsShape);
791 Value res = buildMmaSyncMemRefLoadOperand(b, loc, laneId, resMemRef,
792 resIndexFn, resShape);
793 res =
794 MmaSyncOp::create(b, loc, lhs, rhs, res, info.mmaShape, info.tf32Enabled);
795 buildMmaSyncMemRefStoreOperand(b, loc, res, laneId, resMemRef, resIndexFn,
796 resShape);
797 return res.getDefiningOp();
798}
799
800DiagnosedSilenceableFailure RewriteMatmulAsMmaSyncOp::applyToOne(
801 TransformRewriter &rewriter, LinalgOp linalgOp,
802 ApplyToEachResultList &results, TransformState &state) {
803 bool fail = true;
804 // TODO: more robust detection of matmulOp, with transposes etc.
805 if (isa_and_nonnull<linalg::MatmulOp>(linalgOp.getOperation())) {
806 // Check to not let go the matmul with extended semantic, through this
807 // transform.
808 if (linalgOp.hasUserDefinedMaps()) {
809 return emitSilenceableError()
810 << "only matmul ops with non-extended semantics are supported";
811 }
812 Location loc = linalgOp.getLoc();
813 // TODO: more robust computation of laneId, for now assume a single warp.
814 Value laneId = gpu::ThreadIdOp::create(
815 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
816 if (succeeded(MmaSyncBuilder(rewriter, loc, laneId).buildMmaSync(linalgOp)))
817 fail = false;
818 }
819
820 if (fail) {
821 DiagnosedSilenceableFailure diag = emitSilenceableError()
822 << "unsupported target op: " << linalgOp;
823 diag.attachNote(linalgOp->getLoc()) << "target op";
824 return diag;
825 }
826
827 rewriter.eraseOp(linalgOp);
829}
830
831//===----------------------------------------------------------------------===//
832// Hopper builders.
833//===----------------------------------------------------------------------===//
834
835/// Helper to create the base Hopper-specific operations that are reused in
836/// various other places.
840
843
844 /// Create tma descriptor op to initiate transfer from global to shared
845 /// memory. This must be done before the launch op, on the host.
848 gpu::LaunchOp launchOp);
849
850 /// Build a tma load from global memory to shared memory using `barrier` to
851 /// synchronize. Return the number of bytes that will be transferred.
853 TypedValue<MemRefType> sharedMemref,
858
859 /// If threadIdx.x == 0 does TMA request + wait, else just wait.
860 /// Return the operation that performs the transfer on thread0.
861 // TODO: In the future, don't hardcode to thread 0 but elect a leader.
864 ArrayRef<TypedValue<MemRefType>> sharedMemBuffers,
866
868
871};
872
875 ArrayRef<TypedValue<MemRefType>> sharedMemBuffers,
879 Value tidx = gpu::ThreadIdOp::create(rewriter, loc, gpu::Dimension::x);
880 Value cond = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
881 tidx, zero);
882 // clang-format off
883 scf::IfOp::create(rewriter,
884 /*location=*/loc,
885 /*conditional=*/cond,
886 /*thenBuilder=*/
887 [&](OpBuilder &lb, Location loc) {
889 sizes.reserve(globalDescriptors.size());
890 for (auto [desc, shmem] : llvm::zip_equal(
891 globalDescriptors, sharedMemBuffers)) {
892 OpFoldResult sz = buildTmaAsyncLoad(desc, shmem, barrier, loadOps);
893 sizes.push_back(sz);
894 }
895 // TODO: Note that cutlass predeclares the barrier arrive tx before the tma.async.load.
896 // This may or may not have perf implications.
897 buildBarrierArriveTx(barrier, sizes);
898 scf::YieldOp::create(rewriter, loc);
899 },
900 /*elseBuilder=*/
901 [&](OpBuilder &lb, Location loc) {
902 // TODO: is this for no-thread divergence?
903 // Should we just yield the size and hoist?
904 buildBarrierArriveTx(barrier, getAsIndexOpFoldResult(rewriter.getContext(), 0));
905 scf::YieldOp::create(rewriter, loc);
906 });
907 // clang-format on
908 return loadOps;
909}
910
912 return gpu::AddressSpaceAttr::get(
913 b.getContext(), gpu::GPUDialect::getWorkgroupAddressSpace());
914 // return b.getI64IntegerAttr(static_cast<int64_t>(kSharedMemorySpace));
915}
916
919 auto sharedMemorySpace = getSharedAddressSpaceAttribute(rewriter);
920 Value barrier = MBarrierCreateOp::create(
921 rewriter, loc,
922 MBarrierGroupType::get(rewriter.getContext(), sharedMemorySpace));
924 nvgpu::MBarrierInitOp::create(
925 rewriter, loc, barrier,
926 getValueOrCreateConstantIndexOp(rewriter, loc, numThreads), zero,
927 Value());
928 gpu::BarrierOp::create(rewriter, loc);
929 return cast<TypedValue<MBarrierGroupType>>(barrier);
930}
931
934 gpu::LaunchOp launchOp) {
936 rewriter.setInsertionPoint(launchOp);
937 Value unrankedMemRef = memref::CastOp::create(
938 rewriter, loc,
939 UnrankedMemRefType::get(memref.getType().getElementType(),
940 memref.getType().getMemorySpace()),
941 memref);
942 SmallVector<OpFoldResult> mixedSizes =
944 SmallVector<Value> sizes =
946
947 auto sharedMemorySpace = getSharedAddressSpaceAttribute(rewriter);
948 Value desc = TmaCreateDescriptorOp::create(
949 rewriter, loc,
950 TensorMapDescriptorType::get(rewriter.getContext(),
951 MemRefType::Builder(memref.getType())
952 .setMemorySpace(sharedMemorySpace),
953 TensorMapSwizzleKind::SWIZZLE_NONE,
954 TensorMapL2PromoKind::L2PROMO_NONE,
955 TensorMapOOBKind::OOB_ZERO,
956 TensorMapInterleaveKind::INTERLEAVE_NONE),
957 unrankedMemRef, sizes);
958 return cast<TypedValue<TensorMapDescriptorType>>(desc);
959}
960
963 TypedValue<MemRefType> sharedMemref,
966 MLIRContext *ctx = rewriter.getContext();
968 Operation *loadOp =
969 TmaAsyncLoadOp::create(rewriter, loc, sharedMemref, barrier, globalDesc,
970 ValueRange{zero, zero}, zero, Value(), Value());
971 loadOps.push_back(loadOp);
972 auto mixedSizes = memref::getMixedSizes(rewriter, loc, sharedMemref);
973 SmallVector<AffineExpr> symbols(mixedSizes.size());
975 AffineExpr prodExprInBytes =
976 computeProduct(ctx, symbols) *
977 (sharedMemref.getType().getElementTypeBitWidth() / 8);
979 prodExprInBytes, mixedSizes);
980 return res;
981}
982
984 ArrayRef<OpFoldResult> mixedSizes) {
985 assert(!mixedSizes.empty() && "expecte non-empty sizes");
986 MLIRContext *ctx = rewriter.getContext();
987 SmallVector<AffineExpr> symbols(mixedSizes.size());
989 AffineExpr sumExpr = computeSum(ctx, symbols);
990 OpFoldResult size =
994 nvgpu::MBarrierArriveExpectTxOp::create(rewriter, loc, barrier, sizeVal, zero,
995 Value());
996}
997
999 Type i1 = rewriter.getI1Type();
1000 Value parity = LLVM::ConstantOp::create(rewriter, loc, i1, 0);
1001 // 10M is an arbitrary, not too small or too big number to specify the number
1002 // of ticks before retry.
1003 // TODO: hoist this in a default dialect constant.
1004 Value ticksBeforeRetry =
1007 nvgpu::MBarrierTryWaitParityOp::create(rewriter, loc, barrier, parity,
1008 ticksBeforeRetry, zero);
1009}
1010
1011//===----------------------------------------------------------------------===//
1012// RewriteCopyAsTmaOp
1013//===----------------------------------------------------------------------===//
1014
1015/// Helper to create the tma operations corresponding to `linalg::CopyOp`.
1022
1024 MLIRContext *ctx = rewriter.getContext();
1025 if (copyOps.empty())
1026 return SmallVector<Operation *>();
1027
1028 auto launchOp = copyOps.front()->getParentOfType<gpu::LaunchOp>();
1029 assert(launchOp && "expected launch op");
1030
1031 // 1. Init a barrier object in shared memory.
1033 rewriter.setInsertionPoint(copyOps.front());
1034 AffineExpr bx, by, bz;
1035 bindSymbols(ctx, bx, by, bz);
1036 AffineExpr prod = computeProduct(ctx, ArrayRef<AffineExpr>{bx, by, bz});
1038 rewriter, loc, prod,
1039 ArrayRef<OpFoldResult>{launchOp.getBlockSizeX(), launchOp.getBlockSizeY(),
1040 launchOp.getBlockSizeZ()});
1041
1044
1047 for (Operation *op : copyOps) {
1048 auto copyOp = cast<linalg::CopyOp>(op);
1049 auto inMemRef =
1050 cast<TypedValue<MemRefType>>(copyOp.getDpsInputOperand(0)->get());
1051 assert(inMemRef.getType().getRank() == 2 &&
1052 "expected in to be a 2D memref");
1053
1054 // 2. Build global memory descriptor.
1056 buildGlobalMemRefDescriptor(inMemRef, launchOp);
1057 globalDescs.push_back(globalDesc);
1058
1059 // 3. Shared memory and descriptor for the tmp array.
1060 auto shmem =
1061 cast<TypedValue<MemRefType>>(copyOp.getDpsInitOperand(0)->get());
1062 shmems.push_back(shmem);
1063 }
1064
1065 // 4. Load in from global memory to shared memory using tma.
1067 rewriter.setInsertionPoint(copyOps.front());
1068 SmallVector<Operation *> results =
1069 buildPredicateLoadsOnThread0(globalDescs, shmems, barrier);
1070
1071 // 5. Spin-loop until data is ready.
1072 buildTryWaitParity(barrier);
1073
1074 // 6. Erase the ops that have now been rewritten.
1075 for (Operation *op : copyOps)
1076 rewriter.eraseOp(op);
1077
1078 return results;
1079}
1080
1082RewriteCopyAsTmaOp::apply(TransformRewriter &rewriter,
1083 TransformResults &results, TransformState &state) {
1084 auto payloadOps = state.getPayloadOps(getTarget());
1085 gpu::LaunchOp commonLaunchOp;
1086 Operation *firstOp, *failingOp;
1087 if (llvm::any_of(payloadOps, [&](Operation *op) {
1088 if (!commonLaunchOp) {
1089 commonLaunchOp = op->getParentOfType<gpu::LaunchOp>();
1090 firstOp = op;
1091 }
1092 auto fail = !op->getParentOfType<gpu::LaunchOp>() ||
1093 commonLaunchOp != op->getParentOfType<gpu::LaunchOp>() ||
1094 !isa<linalg::CopyOp>(op);
1095 if (fail)
1096 failingOp = op;
1097 return fail;
1098 })) {
1100 emitSilenceableError()
1101 << "target ops must be linalg::CopyOp nested under a common "
1102 "gpu.LaunchOp to be rewritten because the tma descriptors need to "
1103 "be created on the host.\nBut got: "
1104 << *firstOp << "\nand " << *failingOp;
1105 return diag;
1106 }
1107
1108 // TODO: more robust detection of copy, with transposes etc.
1109 CopyBuilder(rewriter, getLoc()).rewrite(llvm::to_vector(payloadOps));
1110
1112}
1113
1114//===----------------------------------------------------------------------===//
1115// Transform op registration
1116//===----------------------------------------------------------------------===//
1117
1118namespace {
1119class NVGPUTransformDialectExtension
1120 : public TransformDialectExtension<NVGPUTransformDialectExtension> {
1121public:
1122 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(NVGPUTransformDialectExtension)
1123
1124 NVGPUTransformDialectExtension() {
1125 declareGeneratedDialect<arith::ArithDialect>();
1126 declareGeneratedDialect<affine::AffineDialect>();
1127 declareGeneratedDialect<NVGPUDialect>();
1128 declareGeneratedDialect<NVVM::NVVMDialect>();
1129 declareGeneratedDialect<vector::VectorDialect>();
1130 registerTransformOps<
1131#define GET_OP_LIST
1132#include "mlir/Dialect/NVGPU/TransformOps/NVGPUTransformOps.cpp.inc"
1133 >();
1134 }
1135};
1136} // namespace
1137
1138#define GET_OP_CLASSES
1139#include "mlir/Dialect/NVGPU/TransformOps/NVGPUTransformOps.cpp.inc"
1140
1142 registry.addExtensions<NVGPUTransformDialectExtension>();
1143}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
auto load
constexpr int kWgmmaSizeM
M size of wgmma.mma_async instruction.
static Attribute getSharedAddressSpaceAttribute(OpBuilder &b)
static bool hasDefaultMemorySpace(BaseMemRefType type)
Returns true if the given type has the default memory space.
static LogicalResult collectStage0PipeliningOps(scf::ForOp forOp, llvm::SmallPtrSet< Operation *, 16 > &ops)
Populate ops with the set of operations that belong to the stage 0 of the pipelined version of the gi...
static std::tuple< DiagnosedSilenceableFailure, scf::ForOp > pipelineForSharedCopies(RewriterBase &rewriter, scf::ForOp forOp, int64_t depth, bool epiloguePeeling)
Applies loop pipelining with the given depth to the given loop so that copies into the shared memory ...
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
static bool isStoreToShared(Operation *op, Value v)
Returns true if the operation is storing the given value into shared memory.
static void foreachIndividualVectorElement(Value vector, ApplyFn applyFn, ReduceFn reduceFn)
Helper functions to create customizable load and stores operations.
static bool hasSharedMemorySpace(BaseMemRefType type)
Returns true if the given type has the shared (workgroup) memory space.
static bool isLoadFromGlobalStoredToShared(Operation *op)
Returns true if the operation is a load from the default memory space the result of which is only sto...
static std::tuple< SmallVector< int64_t >, SmallVector< int64_t >, SmallVector< int64_t > > makeVectorShapes(ArrayRef< int64_t > lhs, ArrayRef< int64_t > rhs, ArrayRef< int64_t > res)
static void getPipelineStages(scf::ForOp forOp, std::vector< std::pair< Operation *, unsigned > > &opsWithPipelineStages, unsigned depth, llvm::SmallPtrSetImpl< Operation * > &stage0Ops)
Hook for the loop pipeliner that populates ops with the stage information as follows:
static void setAsyncWaitGroupsInFlight(OpBuilder &builder, Operation *op, scf::PipeliningOption::PipelinerPart part, unsigned iteration, unsigned depth)
Hook for the loop pipeliner that sets the "num groups in flight" attribute of async wait operations c...
static Operation * replaceOpWithPredicatedOp(RewriterBase &rewriter, Operation *op, Value predicate)
Hook for the loop pipeliner.
static Value getValueLoadedFromGlobal(Operation *op)
Returns the value produced by a load from the default memory space.
static llvm::ManagedStatic< PassManagerOptions > options
static std::optional< VectorShape > vectorShape(Type type)
static LogicalResult fail(function_ref< InFlightDiagnostic()> emitError, const Twine &message)
Reports message through emitError if it is non-null, and returns failure.
Base type for affine expression.
Definition AffineExpr.h:68
AffineExpr floorDiv(uint64_t v) const
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
Attribute getMemorySpace() const
Returns the memory space in which data referred to by this memref resides.
unsigned getMemorySpaceAsInt() const
[deprecated] Returns the memory space in old raw integer representation.
IndexType getIndexType()
Definition Builders.cpp:59
The result of a transform IR operation application.
static DiagnosedSilenceableFailure success()
Constructs a DiagnosedSilenceableFailure in the success state.
static DiagnosedSilenceableFailure definiteFailure()
Constructs a DiagnosedSilenceableFailure in the failure state.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
void addExtensions()
Add the given extensions to the registry.
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
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This is a builder type that keeps local references to arguments.
Builder & setMemorySpace(Attribute newMemorySpace)
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool 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
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
user_range getUsers() const
Definition Value.h:218
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:436
A list of results of applying a transform op with ApplyEachOpTrait to a single payload operation,...
void push_back(Operation *op)
Appends an element to the list.
Base class for extensions of the Transform dialect that supports injecting operations into the Transf...
Local mapping between values defined by a specific op implementing the TransformOpInterface and the p...
This is a special rewriter to be used in transform op implementations, providing additional helper fu...
The state maintained across applications of various ops implementing the TransformOpInterface.
auto getPayloadOps(Value value) const
Returns an iterator that enumerates all ops that the given transform IR value corresponds to.
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given memref value.
Definition MemRefOps.cpp:80
void populateCommonGPUTypeAndAttributeConversions(TypeConverter &typeConverter)
Remap common GPU memory spaces (Workgroup, Private, etc) to LLVM address spaces.
MemRefType getMBarrierMemrefType(MLIRContext *context, MBarrierGroupType barrierType)
Return the memref type that can be used to represent an mbarrier object.
void registerTransformDialectExtension(DialectRegistry &registry)
void createAsyncGroups(RewriterBase &rewriter, Operation *op, bool bypassL1)
Convert global->shared vector transfers to async device copies.
void producesHandle(ResultRange handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
void consumesHandle(MutableArrayRef< OpOperand > handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with the memory effects indicating the operation on the given handle value:
void modifiesPayload(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with the memory effects indicating the access to payload IR resource.
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.
LogicalResult getBackwardSlice(Operation *op, SetVector< Operation * > *backwardSlice, const BackwardSliceOptions &options={})
Fills backwardSlice with the computed backward slice (i.e.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
DiagnosedSilenceableFailure emitSilenceableFailure(Location loc, const Twine &message={})
Emits a silenceable failure with the given message.
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
AffineExpr computeSum(MLIRContext *ctx, ArrayRef< AffineExpr > basis)
Self-explicit.
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
DiagnosedDefiniteFailure emitDefiniteFailure(Location loc, const Twine &message={})
Emits a definite failure with the given message.
void populateNVGPUToNVVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns)
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
Definition AffineExpr.h:327
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
void bindSymbolsList(MLIRContext *ctx, MutableArrayRef< AffineExprTy > exprs)
Definition AffineExpr.h:332
Helper to create the tma operations corresponding to linalg::CopyOp.
SmallVector< Operation * > rewrite(ArrayRef< Operation * > copyOps)
CopyBuilder(RewriterBase &rewriter, Location loc)
void buildBarrierArriveTx(TypedValue< MBarrierGroupType > barrier, ArrayRef< OpFoldResult > sizes)
OpFoldResult buildTmaAsyncLoad(TypedValue< TensorMapDescriptorType > globalDesc, TypedValue< MemRefType > sharedMemref, TypedValue< MBarrierGroupType > barrier, SmallVectorImpl< Operation * > &loadOps)
Build a tma load from global memory to shared memory using barrier to synchronize.
RewriterBase & rewriter
TypedValue< TensorMapDescriptorType > buildGlobalMemRefDescriptor(TypedValue< MemRefType > memref, gpu::LaunchOp launchOp)
Create tma descriptor op to initiate transfer from global to shared memory.
void buildTryWaitParity(TypedValue< MBarrierGroupType > barrier)
TypedValue< MBarrierGroupType > buildAndInitBarrierInSharedMemory(OpFoldResult numThreads)
SmallVector< Operation * > buildPredicateLoadsOnThread0(ArrayRef< TypedValue< TensorMapDescriptorType > > globalDescriptors, ArrayRef< TypedValue< MemRefType > > sharedMemBuffers, TypedValue< MBarrierGroupType > barrier)
If threadIdx.x == 0 does TMA request + wait, else just wait.
HopperBuilder(RewriterBase &rewriter, Location loc)
Helper struct to provide a simple mapping from matmul operations to the corresponding mma....
MmaSyncBuilder(OpBuilder &b, Location loc, OpFoldResult laneId)
std::function< SmallVector< RowColIndexing >(MLIRContext *)> IndexCalculator
FailureOr< Operation * > buildMmaSync(LinalgOp linalgOp)
Create the mma.sync operation corresponding to linalgOp along with all the supporting load/store and ...
Helper struct to encode a pair of row/column indexings in the form of affine expressions.
AffineExpr col() const
RowColIndexing(AffineExpr row, AffineExpr col)
void print(llvm::raw_ostream &os) const
AffineExpr row() const
Options to dictate how loops should be pipelined.
Definition Transforms.h:140