MLIR 24.0.0git
GPUTransformOps.cpp
Go to the documentation of this file.
1//===- GPUTransformOps.cpp - Implementation of GPU 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"
31#include "mlir/IR/Builders.h"
33#include "mlir/IR/IRMapping.h"
34#include "mlir/IR/MLIRContext.h"
36#include "mlir/IR/Visitors.h"
37#include "mlir/Support/LLVM.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/TypeSwitch.h"
42#include "llvm/Support/DebugLog.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/InterleavedRange.h"
45#include "llvm/Support/LogicalResult.h"
46#include <optional>
47#include <type_traits>
48
49using namespace mlir;
50using namespace mlir::gpu;
51using namespace mlir::transform;
52using namespace mlir::transform::gpu;
53
54#define DEBUG_TYPE "gpu-transforms"
55
56//===----------------------------------------------------------------------===//
57// Apply...ConversionPatternsOp
58//===----------------------------------------------------------------------===//
59
60void transform::ApplyGPUToNVVMConversionPatternsOp::populatePatterns(
61 TypeConverter &typeConverter, RewritePatternSet &patterns) {
62 auto &llvmTypeConverter = static_cast<LLVMTypeConverter &>(typeConverter);
63 configureGpuToNVVMTypeConverter(llvmTypeConverter);
64 // Set higher benefit, so patterns will run before generic LLVM lowering.
65 populateGpuToNVVMConversionPatterns(llvmTypeConverter, patterns,
66 getBenefit());
67}
68
69LogicalResult
70transform::ApplyGPUToNVVMConversionPatternsOp::verifyTypeConverter(
71 transform::TypeConverterBuilderOpInterface builder) {
72 if (builder.getTypeConverterType() != "LLVMTypeConverter")
73 return emitOpError("expected LLVMTypeConverter");
74 return success();
75}
76
77void transform::ApplyGPUWwmaToNVVMConversionPatternsOp::populatePatterns(
78 TypeConverter &typeConverter, RewritePatternSet &patterns) {
79 auto &llvmTypeConverter = static_cast<LLVMTypeConverter &>(typeConverter);
80 populateGpuWMMAToNVVMConversionPatterns(llvmTypeConverter, patterns);
81}
82
83LogicalResult
84transform::ApplyGPUWwmaToNVVMConversionPatternsOp::verifyTypeConverter(
85 transform::TypeConverterBuilderOpInterface builder) {
86 if (builder.getTypeConverterType() != "LLVMTypeConverter")
87 return emitOpError("expected LLVMTypeConverter");
88 return success();
89}
90
91void transform::ApplyGPUSubgroupReduceToNVVMConversionPatternsOp::
92 populatePatterns(TypeConverter &typeConverter,
93 RewritePatternSet &patterns) {
94 auto &llvmTypeConverter = static_cast<LLVMTypeConverter &>(typeConverter);
95 populateGpuSubgroupReduceOpLoweringPattern(llvmTypeConverter, patterns);
96}
97
98LogicalResult transform::ApplyGPUSubgroupReduceToNVVMConversionPatternsOp::
99 verifyTypeConverter(transform::TypeConverterBuilderOpInterface builder) {
100 if (builder.getTypeConverterType() != "LLVMTypeConverter")
101 return emitOpError("expected LLVMTypeConverter");
102 return success();
103}
104
105void transform::ApplyGPUToROCDLConversionPatternsOp::populatePatterns(
106 TypeConverter &typeConverter, RewritePatternSet &patterns) {
107 auto &llvmTypeConverter = static_cast<LLVMTypeConverter &>(typeConverter);
109 // The verifier has already rejected anything unparseable.
110 FailureOr<ROCDL::TargetInfo> targetInfo =
111 ROCDL::TargetInfo::get(getArch(), getWavesize().value_or(0));
112 assert(llvm::succeeded(targetInfo) && "verifier accepted this target");
114 llvmTypeConverter, patterns, mlir::gpu::amd::Runtime::HIP, *targetInfo);
115}
116
117LogicalResult
118transform::ApplyGPUToROCDLConversionPatternsOp::verifyTypeConverter(
119 transform::TypeConverterBuilderOpInterface builder) {
120 if (failed(ROCDL::TargetInfo::get(getArch(), getWavesize().value_or(0),
121 [&] { return emitOpError(); })))
122 return failure();
123 if (builder.getTypeConverterType() != "LLVMTypeConverter")
124 return emitOpError("expected LLVMTypeConverter");
125 return success();
126}
127
128//===----------------------------------------------------------------------===//
129// Apply...PatternsOp
130//===----------------------------------------------------------------------===//s
131
132void ApplyGPURewritePatternsOp::populatePatterns(RewritePatternSet &patterns) {
134}
135
136void transform::ApplyGPUPromoteShuffleToAMDGPUPatternsOp::populatePatterns(
137 RewritePatternSet &patterns) {
138 std::optional<StringRef> archName = getArch();
139 std::optional<ROCDL::TargetInfo> targetInfo;
140 if (archName) {
141 // The verifier has already rejected anything unparseable.
142 FailureOr<ROCDL::TargetInfo> parsed = ROCDL::TargetInfo::get(*archName);
143 assert(llvm::succeeded(parsed) && "verifier accepted this target");
144 targetInfo = *parsed;
145 }
146
147 populateGpuPromoteShuffleToAMDGPUPatterns(patterns, targetInfo);
148}
149
150LogicalResult transform::ApplyGPUPromoteShuffleToAMDGPUPatternsOp::verify() {
151 std::optional<StringRef> archName = getArch();
152 if (!archName)
153 return success();
154
155 if (failed(ROCDL::TargetInfo::get(*archName, /*waveSize=*/0,
156 [&] { return emitOpError(); })))
157 return failure();
158 return success();
159}
160
161//===----------------------------------------------------------------------===//
162// EliminateBarriersOp
163//===----------------------------------------------------------------------===//
164
165void EliminateBarriersOp::populatePatterns(RewritePatternSet &patterns) {
167}
168
169//===----------------------------------------------------------------------===//
170// Block and thread mapping utilities.
171//===----------------------------------------------------------------------===//
172
173namespace {
174/// Local types used for mapping verification.
175struct MappingKind {};
176struct BlockMappingKind : MappingKind {};
177struct ThreadMappingKind : MappingKind {};
178} // namespace
179
181definiteFailureHelper(std::optional<TransformOpInterface> transformOp,
182 Operation *target, const Twine &message) {
183 if (transformOp.has_value())
184 return transformOp->emitDefiniteFailure() << message;
185 return emitDefiniteFailure(target, message);
186}
187
188/// Check if given mapping attributes are one of the desired attributes
189template <typename MappingKindType>
191checkMappingAttributeTypes(std::optional<TransformOpInterface> transformOp,
192 scf::ForallOp forallOp) {
193 if (!forallOp.getMapping().has_value()) {
194 return definiteFailureHelper(transformOp, forallOp,
195 "scf.forall op requires a mapping attribute");
196 }
197
198 bool hasBlockMapping = llvm::any_of(forallOp.getMapping().value(),
199 llvm::IsaPred<GPUBlockMappingAttr>);
200 bool hasWarpgroupMapping = llvm::any_of(
201 forallOp.getMapping().value(), llvm::IsaPred<GPUWarpgroupMappingAttr>);
202 bool hasWarpMapping = llvm::any_of(forallOp.getMapping().value(),
203 llvm::IsaPred<GPUWarpMappingAttr>);
204 bool hasThreadMapping = llvm::any_of(forallOp.getMapping().value(),
205 llvm::IsaPred<GPUThreadMappingAttr>);
206 bool hasLaneMapping = llvm::any_of(forallOp.getMapping().value(),
207 llvm::IsaPred<GPULaneMappingAttr>);
208 int64_t countMappingTypes = 0;
209 countMappingTypes += hasBlockMapping ? 1 : 0;
210 countMappingTypes += hasWarpgroupMapping ? 1 : 0;
211 countMappingTypes += hasWarpMapping ? 1 : 0;
212 countMappingTypes += hasThreadMapping ? 1 : 0;
213 countMappingTypes += hasLaneMapping ? 1 : 0;
214 if (countMappingTypes > 1) {
216 transformOp, forallOp,
217 "cannot mix different mapping types, use nesting");
218 }
219 if (std::is_same<MappingKindType, BlockMappingKind>::value &&
220 !hasBlockMapping) {
222 transformOp, forallOp,
223 "scf.forall op requires a mapping attribute of kind 'block'");
224 }
225 if (std::is_same<MappingKindType, ThreadMappingKind>::value &&
226 !hasLaneMapping && !hasThreadMapping && !hasWarpMapping &&
227 !hasWarpgroupMapping) {
228 return definiteFailureHelper(transformOp, forallOp,
229 "scf.forall op requires a mapping attribute "
230 "of kind 'thread' or 'warp'");
231 }
232
234 for (Attribute map : forallOp.getMapping()->getValue()) {
235 if (seen.contains(map)) {
237 transformOp, forallOp,
238 "duplicate attribute, cannot map different loops "
239 "to the same mapping id");
240 }
241 seen.insert(map);
242 }
243
244 auto isLinear = [](DeviceMappingAttrInterface attr) {
245 return attr.isLinearMapping();
246 };
247 if (llvm::any_of(forallOp.getDeviceMappingAttrs(), isLinear) &&
248 !llvm::all_of(forallOp.getDeviceMappingAttrs(), isLinear)) {
250 transformOp, forallOp,
251 "cannot mix linear and non-linear mapping modes");
252 }
253
254 FailureOr<DeviceMaskingAttrInterface> maybeMaskingAttr =
255 forallOp.getDeviceMaskingAttr();
256 if (succeeded(maybeMaskingAttr) && *maybeMaskingAttr &&
257 !forallOp.usesLinearMapping()) {
259 transformOp, forallOp,
260 "device masking is only available in linear mapping mode");
261 }
262
264}
265
266template <typename MappingKindType>
268verifyGpuMapping(std::optional<TransformOpInterface> transformOp,
269 scf::ForallOp forallOp) {
270 // Check the types of the mapping attributes match.
272 checkMappingAttributeTypes<MappingKindType>(transformOp, forallOp);
273 if (!typeRes.succeeded())
274 return typeRes;
275
276 // Perform other non-types verifications.
277 if (!forallOp.isNormalized())
278 return definiteFailureHelper(transformOp, forallOp,
279 "unsupported non-normalized loops");
280 if (forallOp.getNumResults() > 0)
281 return definiteFailureHelper(transformOp, forallOp,
282 "only bufferized scf.forall can be mapped");
283 bool useLinearMapping = forallOp.usesLinearMapping();
284 // TODO: This would be more natural with support for Optional<EnumParameter>
285 // in GPUDeviceMappingAttr.
286 int64_t maxNumMappingsSupported =
287 useLinearMapping ? (getMaxEnumValForMappingId() -
288 static_cast<uint64_t>(MappingId::DimZ))
289 : 3;
290 if (forallOp.getRank() > maxNumMappingsSupported) {
291 return definiteFailureHelper(transformOp, forallOp,
292 "scf.forall with rank > ")
293 << maxNumMappingsSupported
294 << " does not lower for the specified mapping attribute type";
295 }
296 auto numParallelIterations =
297 getConstantIntValues(forallOp.getMixedUpperBound());
298 if (!forallOp.isNormalized() || !numParallelIterations.has_value()) {
300 transformOp, forallOp,
301 "requires statically sized, normalized forall op");
302 }
304}
305
306/// Struct to return the result of the rewrite of a forall operation.
311
312/// Helper to replace ids of dimensions known to be 1 by 0 to simplify the IR.
313template <typename OpTy, typename OperationOrBlock>
314static void
316 OperationOrBlock *parent, Value replacement,
317 ArrayRef<int64_t> availableMappingSizes) {
318 parent->walk([&](OpTy idOp) {
319 if (availableMappingSizes[static_cast<int64_t>(idOp.getDimension())] == 1)
320 rewriter.replaceAllUsesWith(idOp.getResult(), replacement);
321 });
322}
323
325 RewriterBase &rewriter, std::optional<TransformOpInterface> transformOp,
326 scf::ForallOp forallOp, ArrayRef<int64_t> availableMappingSizes,
327 ForallRewriteResult &result, const GpuIdBuilder &gpuIdBuilder) {
328 LDBG() << "--start rewriteOneForallCommonImpl";
329
330 // Step 1. Complete the mapping to a full mapping (with 1s) if necessary.
331 auto numParallelIterations =
332 getConstantIntValues(forallOp.getMixedUpperBound());
333 assert(forallOp.isNormalized() && numParallelIterations.has_value() &&
334 "requires statically sized, normalized forall op");
335 SmallVector<int64_t> tmpMappingSizes = numParallelIterations.value();
336 SmallVector<DeviceMappingAttrInterface> forallMappingAttrsVec =
337 forallOp.getDeviceMappingAttrs();
338 SetVector<Attribute> forallMappingAttrs;
339 forallMappingAttrs.insert_range(forallMappingAttrsVec);
340 auto comparator = [](Attribute a, Attribute b) -> bool {
341 return cast<DeviceMappingAttrInterface>(a).getMappingId() <
342 cast<DeviceMappingAttrInterface>(b).getMappingId();
343 };
344
345 // Step 1.b. In the linear case, compute the max mapping to avoid needlessly
346 // mapping all dimensions. In the 3-D mapping case we need to map all
347 // dimensions.
348 DeviceMappingAttrInterface maxMapping = cast<DeviceMappingAttrInterface>(
349 *llvm::max_element(forallMappingAttrs, comparator));
350 DeviceMappingAttrInterface maxLinearMapping;
351 if (maxMapping.isLinearMapping())
352 maxLinearMapping = maxMapping;
353 for (auto attr : gpuIdBuilder.mappingAttributes) {
354 // If attr overflows, just skip.
355 if (maxLinearMapping && comparator(maxLinearMapping, attr))
356 continue;
357 // Try to insert. If element was already present, just continue.
358 if (!forallMappingAttrs.insert(attr))
359 continue;
360 // Otherwise, we have a new insertion without a size -> use size 1.
361 tmpMappingSizes.push_back(1);
362 }
363 LDBG() << "----tmpMappingSizes extracted from scf.forall op: "
364 << llvm::interleaved(tmpMappingSizes);
365
366 // Step 2. sort the values by the corresponding DeviceMappingAttrInterface.
367 SmallVector<int64_t> forallMappingSizes = getValuesSortedByKey(
368 forallMappingAttrs.getArrayRef(), tmpMappingSizes, comparator);
369 LDBG() << "----forallMappingSizes: " << llvm::interleaved(forallMappingSizes);
370 LDBG() << "----forallMappingAttrs: " << llvm::interleaved(forallMappingAttrs);
371
372 // Step 3. Generate the mappingIdOps using the provided generator.
373 Location loc = forallOp.getLoc();
374 OpBuilder::InsertionGuard guard(rewriter);
375 rewriter.setInsertionPoint(forallOp);
376 SmallVector<int64_t> originalBasis(availableMappingSizes);
377 bool originalBasisWasProvided = !originalBasis.empty();
378 if (!originalBasisWasProvided) {
379 LDBG() << "----originalBasis was not provided, deriving it and there will "
380 "be no "
381 "predication";
382 originalBasis = forallMappingSizes;
383 while (originalBasis.size() < 3)
384 originalBasis.push_back(1);
385 } else {
386 LDBG() << "----originalBasis was provided, using it, there will be "
387 "predication";
388 }
389 LDBG() << "------originalBasis: " << llvm::interleaved(originalBasis);
390
391 IdBuilderResult builderResult =
392 gpuIdBuilder.idBuilder(rewriter, loc, forallMappingSizes, originalBasis);
393 if (!builderResult.errorMsg.empty())
394 return definiteFailureHelper(transformOp, forallOp, builderResult.errorMsg);
395
396 LDBG() << builderResult;
397
398 // Step 4. Map the induction variables to the mappingIdOps, this may involve
399 // a permutation.
400 SmallVector<Value> mappingIdOps = builderResult.mappingIdOps;
401 IRMapping bvm;
402 for (auto [iv, dim] : llvm::zip_equal(
403 forallOp.getInductionVars(),
404 forallMappingAttrs.getArrayRef().take_front(forallOp.getRank()))) {
405 auto mappingAttr = cast<DeviceMappingAttrInterface>(dim);
406 Value peIdOp = mappingIdOps[mappingAttr.getRelativeIndex()];
407 LDBG() << "----map: " << iv << " to " << peIdOp;
408 bvm.map(iv, peIdOp);
409 }
410
411 // Step 5. If the originalBasis is already known, create conditionals to
412 // predicate the region. Otherwise, the current forall determines the
413 // originalBasis and no predication occurs.
414 Value predicate;
415 if (originalBasisWasProvided) {
416 for (Value tmpPredicate : builderResult.predicateOps) {
417 predicate = predicate ? arith::AndIOp::create(rewriter, loc, predicate,
418 tmpPredicate)
419 : tmpPredicate;
420 }
421 }
422
423 // Step 6. Move the body of forallOp.
424 // Erase the terminator first, it will not be used.
425 rewriter.eraseOp(forallOp.getTerminator());
426 Block *targetBlock;
427 Block::iterator insertionPoint;
428 if (predicate) {
429 // Step 6.a. If predicated, move at the beginning.
430 auto ifOp = scf::IfOp::create(rewriter, loc, predicate,
431 /*withElseRegion=*/false);
432 targetBlock = ifOp.thenBlock();
433 insertionPoint = ifOp.thenBlock()->begin();
434 } else {
435 // Step 6.b. Otherwise, move inline just at the rewriter insertion
436 // point.
437 targetBlock = forallOp->getBlock();
438 insertionPoint = rewriter.getInsertionPoint();
439 }
440 Block &sourceBlock = forallOp.getRegion().front();
441 targetBlock->getOperations().splice(insertionPoint,
442 sourceBlock.getOperations());
443
444 // Step 7. RAUW indices.
445 for (Value loopIndex : forallOp.getInductionVars()) {
446 Value threadIdx = bvm.lookup(loopIndex);
447 rewriter.replaceAllUsesWith(loopIndex, threadIdx);
448 }
449
450 // Step 8. Erase old op.
451 rewriter.eraseOp(forallOp);
452
453 LDBG() << "----result forallMappingSizes: "
454 << llvm::interleaved(forallMappingSizes);
455 LDBG() << "----result mappingIdOps: " << llvm::interleaved(mappingIdOps);
456
457 result = ForallRewriteResult{forallMappingSizes, mappingIdOps};
459}
460
461//===----------------------------------------------------------------------===//
462// MapForallToBlocks
463//===----------------------------------------------------------------------===//
464
466 RewriterBase &rewriter, TransformOpInterface transformOp,
467 scf::ForallOp forallOp, SmallVectorImpl<int64_t> &gridDims,
468 const GpuIdBuilder &gpuIdBuilder) {
469 LDBG() << "Start mapForallToBlocksImpl";
470
471 {
472 // GPU-specific verifications. There is no better place to anchor
473 // those right now: the ForallOp is target-independent and the transform
474 // op does not apply to individual ForallOp.
476 verifyGpuMapping<BlockMappingKind>(transformOp, forallOp);
477 if (!diag.succeeded())
478 return diag;
479 }
480
481 Location loc = forallOp.getLoc();
482 Block *parentBlock = forallOp->getBlock();
483 Value zero;
484 {
485 // Create an early zero index value for replacements and immediately reset
486 // the insertion point.
487 OpBuilder::InsertionGuard guard(rewriter);
488 rewriter.setInsertionPointToStart(parentBlock);
489 zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
490 }
491
492 ForallRewriteResult rewriteResult;
494 rewriter, transformOp, forallOp,
495 /*availableMappingSizes=*/gridDims, rewriteResult, gpuIdBuilder);
496
497 // Return if anything goes wrong, use silenceable failure as a match
498 // failure.
499 if (!diag.succeeded())
500 return diag;
501
502 // If gridDims was not provided already, set it from the return.
503 if (gridDims.empty()) {
504 gridDims = rewriteResult.mappingSizes;
505 while (gridDims.size() < 3)
506 gridDims.push_back(1);
507 }
508 assert(gridDims.size() == 3 && "Need 3-D gridDims");
509
510 // Replace ids of dimensions known to be 1 by 0 to simplify the IR.
511 // Here, the result of mapping determines the available mapping sizes.
512 replaceUnitMappingIdsHelper<BlockDimOp>(rewriter, loc, parentBlock, zero,
513 rewriteResult.mappingSizes);
514
516}
517
520 scf::ForallOp &topLevelForallOp,
521 TransformOpInterface transformOp) {
522 auto walkResult = target->walk([&](scf::ForallOp forallOp) {
523 if (forallOp->getParentOfType<scf::ForallOp>())
524 return WalkResult::advance();
525 if (topLevelForallOp)
526 // TODO: Handle multiple forall if they are independent.
527 return WalkResult::interrupt();
528 topLevelForallOp = forallOp;
529 return WalkResult::advance();
530 });
531
532 if (walkResult.wasInterrupted() || !topLevelForallOp)
533 return transformOp.emitSilenceableError()
534 << "could not find a unique topLevel scf.forall";
536}
537
538DiagnosedSilenceableFailure transform::MapForallToBlocks::applyToOne(
541 LaunchOp gpuLaunch = dyn_cast<LaunchOp>(target);
542 auto transformOp = cast<TransformOpInterface>(getOperation());
543
544 if (!getGenerateGpuLaunch() && !gpuLaunch) {
546 emitSilenceableError()
547 << "Given target is not gpu.launch, set `generate_gpu_launch` "
548 "attribute";
549 diag.attachNote(target->getLoc()) << "when applied to this payload op";
550 return diag;
551 }
552
553 scf::ForallOp topLevelForallOp;
555 target, topLevelForallOp, transformOp);
556 if (!diag.succeeded()) {
557 diag.attachNote(target->getLoc()) << "when applied to this payload op";
558 return diag;
559 }
560 assert(topLevelForallOp && "expect an scf.forall");
561
562 SmallVector<int64_t> gridDims{getGridDims()};
563 if (!getGenerateGpuLaunch() && gridDims.size() != 3)
564 return transformOp.emitDefiniteFailure("transform require size-3 mapping");
565
566 OpBuilder::InsertionGuard guard(rewriter);
567 rewriter.setInsertionPoint(topLevelForallOp);
568
569 // Generate gpu launch here and move the forall inside
570 if (getGenerateGpuLaunch()) {
572 createGpuLaunch(rewriter, target->getLoc(), transformOp, gpuLaunch);
573 if (!diag.succeeded())
574 return diag;
575
576 rewriter.setInsertionPointToStart(&gpuLaunch.getBody().front());
577 Operation *newForallOp = rewriter.clone(*topLevelForallOp);
578 rewriter.eraseOp(topLevelForallOp);
579 topLevelForallOp = cast<scf::ForallOp>(newForallOp);
580 }
581
582 // The BlockIdBuilder adapts to whatever is thrown at it.
583 bool useLinearMapping = false;
584 if (topLevelForallOp.getMapping())
585 useLinearMapping = topLevelForallOp.usesLinearMapping();
586
587 FailureOr<DeviceMaskingAttrInterface> maybeMaskingAttr =
588 topLevelForallOp.getDeviceMaskingAttr();
589 assert(succeeded(maybeMaskingAttr) && "unexpected failed maybeMaskingAttr");
590 assert((!*maybeMaskingAttr || useLinearMapping) &&
591 "masking requires linear mapping");
592
593 GpuBlockIdBuilder gpuBlockIdBuilder(getContext(), useLinearMapping,
594 *maybeMaskingAttr);
595
597 rewriter, transformOp, topLevelForallOp, gridDims, gpuBlockIdBuilder);
598 if (!diag.succeeded())
599 return diag;
600
601 // Set the GPU launch configuration for the grid dims late, this is
602 // subject to IR inspection.
603 diag = alterGpuLaunch(rewriter, gpuLaunch,
604 cast<TransformOpInterface>(getOperation()), gridDims[0],
605 gridDims[1], gridDims[2]);
606
607 results.push_back(gpuLaunch);
608 return diag;
609}
610
611LogicalResult transform::MapForallToBlocks::verify() {
612 if (!getGridDims().empty() && getGridDims().size() != 3) {
613 return emitOpError() << "transform requires empty or size-3 grid_dims";
614 }
615 return success();
616}
617
618//===----------------------------------------------------------------------===//
619// MapNestedForallToThreads
620//===----------------------------------------------------------------------===//
621
623 std::optional<TransformOpInterface> transformOp, scf::ForallOp forallOp,
624 ArrayRef<int64_t> numParallelIterations, ArrayRef<int64_t> blockOrGridSizes,
625 int factor, bool useLinearMapping = false) {
626 if (llvm::any_of(blockOrGridSizes, [](int64_t i) { return i <= 0; })) {
627 return definiteFailureHelper(transformOp, forallOp,
628 "block/grid sizes must be strictly positive");
629 }
630 if (!useLinearMapping && blockOrGridSizes.front() % factor != 0) {
632 transformOp, forallOp,
633 Twine("3-D mapping: size of threadIdx.x must be a multiple of ") +
634 Twine(factor));
635 return diag;
636 }
637 bool hasZeroParallelIteration =
638 llvm::any_of(numParallelIterations, [](int64_t i) { return i == 0; });
639 // `computeProduct` requires strictly positive inputs, so handle the
640 // zero-iteration case explicitly to avoid asserting on valid degenerate
641 // loop bounds.
642 int64_t requiredResourceCount =
643 hasZeroParallelIteration ? 0
644 : computeProduct(numParallelIterations) * factor;
645 int64_t availableResourceCount = computeProduct(blockOrGridSizes);
646 if (requiredResourceCount > availableResourceCount) {
648 transformOp, forallOp,
649 Twine("the number of required parallel resources (blocks or "
650 "threads) ") +
651 Twine(requiredResourceCount) +
652 " overflows the number of available resources " +
653 Twine(availableResourceCount));
654 return diag;
655 }
657}
658
660getThreadIdBuilder(std::optional<TransformOpInterface> transformOp,
661 scf::ForallOp forallOp, ArrayRef<int64_t> blockSizes,
662 int64_t warpSize, GpuIdBuilder &gpuIdBuilder) {
663 DeviceMappingAttrInterface mappingAttr =
664 forallOp.getDeviceMappingAttrs().front();
665 bool useLinearMapping = mappingAttr.isLinearMapping();
666
667 // Sanity checks that may result in runtime verification errors.
668 auto numParallelIterations =
669 getConstantIntValues((forallOp.getMixedUpperBound()));
670 if (!forallOp.isNormalized() || !numParallelIterations.has_value()) {
672 transformOp, forallOp,
673 "requires statically sized, normalized forall op");
674 }
675 int64_t factor = 1;
676 if (isa<GPUWarpgroupMappingAttr>(mappingAttr)) {
678 } else if (isa<GPUWarpMappingAttr>(mappingAttr)) {
679 factor = warpSize;
680 }
682 checkMappingSpec(transformOp, forallOp, numParallelIterations.value(),
683 blockSizes, factor, useLinearMapping);
684 if (!diag.succeeded())
685 return diag;
686
687 FailureOr<DeviceMaskingAttrInterface> maybeMaskingAttr =
688 forallOp.getDeviceMaskingAttr();
689 assert(succeeded(maybeMaskingAttr) && "unexpected failed maybeMaskingAttr");
690 assert((!*maybeMaskingAttr || useLinearMapping) &&
691 "masking requires linear mapping");
692
693 // Start mapping.
694 MLIRContext *ctx = forallOp.getContext();
695 gpuIdBuilder =
697 .Case([&](GPUWarpgroupMappingAttr) {
698 return GpuWarpgroupIdBuilder(ctx, warpSize, useLinearMapping,
699 *maybeMaskingAttr);
700 })
701 .Case([&](GPUWarpMappingAttr) {
702 return GpuWarpIdBuilder(ctx, warpSize, useLinearMapping,
703 *maybeMaskingAttr);
704 })
705 .Case([&](GPUThreadMappingAttr) {
706 return GpuThreadIdBuilder(ctx, useLinearMapping, *maybeMaskingAttr);
707 })
708 .Case([&](GPULaneMappingAttr) {
709 return GpuLaneIdBuilder(ctx, warpSize, useLinearMapping,
710 *maybeMaskingAttr);
711 })
712 .DefaultUnreachable("unknown mapping attribute");
714}
715
717 RewriterBase &rewriter, std::optional<TransformOpInterface> transformOp,
718 scf::ForallOp forallOp, ArrayRef<int64_t> blockSizes, int64_t warpSize,
719 bool syncAfterDistribute) {
720
721 {
722 // GPU-specific verifications. There is no better place to anchor
723 // those right now: the ForallOp is target-independent and the transform
724 // op does not apply to individual ForallOp.
726 verifyGpuMapping<ThreadMappingKind>(transformOp, forallOp);
727 if (!diag.succeeded())
728 return diag;
729 }
730
731 GpuIdBuilder gpuIdBuilder;
732 {
733 // Try to construct the id builder, if it fails, return.
735 transformOp, forallOp, blockSizes, warpSize, gpuIdBuilder);
736 if (!diag.succeeded())
737 return diag;
738 }
739
740 Location loc = forallOp.getLoc();
741 OpBuilder::InsertionGuard g(rewriter);
742 // Insert after to allow for syncthreads after `forall` is erased.
743 rewriter.setInsertionPointAfter(forallOp);
744 ForallRewriteResult rewriteResult;
746 rewriter, transformOp, forallOp, blockSizes, rewriteResult, gpuIdBuilder);
747 if (!diag.succeeded())
748 return diag;
749 // Add a syncthreads if needed. TODO: warpsync
750 if (syncAfterDistribute)
751 BarrierOp::create(rewriter, loc);
752
754}
755
757 RewriterBase &rewriter, std::optional<TransformOpInterface> transformOp,
758 Operation *target, ArrayRef<int64_t> blockDims, int64_t warpSize,
759 bool syncAfterDistribute) {
760 LDBG() << "Start mapNestedForallToThreadsImpl";
761 if (blockDims.size() != 3) {
762 return definiteFailureHelper(transformOp, target,
763 "requires size-3 thread mapping");
764 }
765
766 // Create an early zero index value for replacements.
767 Location loc = target->getLoc();
768 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
770 WalkResult walkResult = target->walk([&](scf::ForallOp forallOp) {
772 rewriter, transformOp, forallOp, blockDims, warpSize,
773 syncAfterDistribute);
774 if (diag.isDefiniteFailure())
775 return WalkResult::interrupt();
776 if (diag.succeeded())
777 return WalkResult::skip();
778 return WalkResult::advance();
779 });
780 if (walkResult.wasInterrupted())
781 return diag;
782
783 // Replace ids of dimensions known to be 1 by 0 to simplify the IR.
784 // Here, the result of mapping determines the available mapping sizes.
786 blockDims);
787
789}
790
791DiagnosedSilenceableFailure transform::MapNestedForallToThreads::applyToOne(
793 ApplyToEachResultList &results, TransformState &state) {
794 LaunchOp gpuLaunch = dyn_cast<LaunchOp>(target);
795 auto transformOp = cast<TransformOpInterface>(getOperation());
796
797 // Basic high-level verifications.
798 if (!gpuLaunch)
799 return emitSilenceableError() << "Given target is not a gpu.launch";
800
801 // Mapping to block ids.
802 SmallVector<int64_t> blockDims{getBlockDims()};
804 checkGpuLimits(transformOp, std::nullopt, std::nullopt, std::nullopt,
805 blockDims[0], blockDims[1], blockDims[2]);
806 if (diag.isSilenceableFailure()) {
807 diag.attachNote(getLoc()) << getBlockDimsAttrName() << " is too large";
808 return diag;
809 }
810
811 // Set the GPU launch configuration for the block dims early, this is not
812 // subject to IR inspection.
813 diag = alterGpuLaunch(rewriter, gpuLaunch, transformOp, std::nullopt,
814 std::nullopt, std::nullopt, blockDims[0], blockDims[1],
815 blockDims[2]);
816
817 rewriter.setInsertionPointToStart(&gpuLaunch.getBody().front());
818 diag =
819 mapNestedForallToThreadsImpl(rewriter, transformOp, gpuLaunch, blockDims,
820 getWarpSize(), getSyncAfterDistribute());
821
822 results.push_back(gpuLaunch.getOperation());
823 return diag;
824}
825
826//===----------------------------------------------------------------------===//
827// Transform op registration
828//===----------------------------------------------------------------------===//
829
830namespace {
831/// Registers new ops and declares PDL as dependent dialect since the
832/// additional ops are using PDL types for operands and results.
833class GPUTransformDialectExtension
835 GPUTransformDialectExtension> {
836public:
837 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GPUTransformDialectExtension)
838
839 GPUTransformDialectExtension() {
840 declareGeneratedDialect<GPUDialect>();
841 declareGeneratedDialect<amdgpu::AMDGPUDialect>();
842 declareGeneratedDialect<arith::ArithDialect>();
843 declareGeneratedDialect<scf::SCFDialect>();
844 registerTransformOps<
845#define GET_OP_LIST
846#include "mlir/Dialect/GPU/TransformOps/GPUTransformOps.cpp.inc"
847 >();
848 }
849};
850} // namespace
851
852#define GET_OP_CLASSES
853#include "mlir/Dialect/GPU/TransformOps/GPUTransformOps.cpp.inc"
854
856 registry.addExtensions<GPUTransformDialectExtension>();
857}
return success()
static DiagnosedSilenceableFailure checkMappingAttributeTypes(std::optional< TransformOpInterface > transformOp, scf::ForallOp forallOp)
Check if given mapping attributes are one of the desired attributes.
static DiagnosedSilenceableFailure rewriteOneForallCommonImpl(RewriterBase &rewriter, std::optional< TransformOpInterface > transformOp, scf::ForallOp forallOp, ArrayRef< int64_t > availableMappingSizes, ForallRewriteResult &result, const GpuIdBuilder &gpuIdBuilder)
static DiagnosedSilenceableFailure definiteFailureHelper(std::optional< TransformOpInterface > transformOp, Operation *target, const Twine &message)
static DiagnosedSilenceableFailure checkMappingSpec(std::optional< TransformOpInterface > transformOp, scf::ForallOp forallOp, ArrayRef< int64_t > numParallelIterations, ArrayRef< int64_t > blockOrGridSizes, int factor, bool useLinearMapping=false)
static void replaceUnitMappingIdsHelper(RewriterBase &rewriter, Location loc, OperationOrBlock *parent, Value replacement, ArrayRef< int64_t > availableMappingSizes)
Helper to replace ids of dimensions known to be 1 by 0 to simplify the IR.
static DiagnosedSilenceableFailure verifyGpuMapping(std::optional< TransformOpInterface > transformOp, scf::ForallOp forallOp)
static DiagnosedSilenceableFailure getThreadIdBuilder(std::optional< TransformOpInterface > transformOp, scf::ForallOp forallOp, ArrayRef< int64_t > blockSizes, int64_t warpSize, GpuIdBuilder &gpuIdBuilder)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
*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 the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
Definition TypeID.h:331
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
OpListType::iterator iterator
Definition Block.h:165
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
iterator begin()
Definition Block.h:168
The result of a transform IR operation application.
static DiagnosedSilenceableFailure success()
Constructs a DiagnosedSilenceableFailure in the success state.
bool succeeded() const
Returns true if this is a success.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
void addExtensions()
Add the given extensions to the registry.
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
auto lookup(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:72
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
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
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Definition Builders.h:448
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
static FailureOr< TargetInfo > get(StringRef arch, unsigned waveSize=0, function_ref< InFlightDiagnostic()> emitError=nullptr)
Resolves a target description.
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.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
bool wasInterrupted() const
Returns true if the walk was interrupted.
Definition WalkResult.h:51
static WalkResult interrupt()
Definition WalkResult.h:46
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
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...
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.
void populateCommonGPUTypeAndAttributeConversions(TypeConverter &typeConverter)
Remap common GPU memory spaces (Workgroup, Private, etc) to LLVM address spaces.
void registerTransformDialectExtension(DialectRegistry &registry)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
DiagnosedSilenceableFailure findTopLevelForallOp(Operation *target, scf::ForallOp &topLevelForallOp, TransformOpInterface transformOp)
Find the unique top level scf::ForallOp within a given target op.
DiagnosedSilenceableFailure alterGpuLaunch(RewriterBase &rewriter, mlir::gpu::LaunchOp gpuLaunch, TransformOpInterface transformOp, std::optional< int64_t > gridDimX=std::nullopt, std::optional< int64_t > gridDimY=std::nullopt, std::optional< int64_t > gridDimZ=std::nullopt, std::optional< int64_t > blockDimX=std::nullopt, std::optional< int64_t > blockDimY=std::nullopt, std::optional< int64_t > blockDimZ=std::nullopt)
Alter kernel configuration of the given kernel.
DiagnosedSilenceableFailure createGpuLaunch(RewriterBase &rewriter, Location loc, TransformOpInterface transformOp, mlir::gpu::LaunchOp &launchOp, std::optional< int64_t > gridDimX=std::nullopt, std::optional< int64_t > gridDimY=std::nullopt, std::optional< int64_t > gridDimZ=std::nullopt, std::optional< int64_t > blockDimX=std::nullopt, std::optional< int64_t > blockDimY=std::nullopt, std::optional< int64_t > blockDimZ=std::nullopt)
Create an empty-body gpu::LaunchOp using the provided kernel settings and put a terminator within.
DiagnosedSilenceableFailure mapForallToBlocksImpl(RewriterBase &rewriter, TransformOpInterface transformOp, scf::ForallOp forallOp, SmallVectorImpl< int64_t > &gridDims, const GpuIdBuilder &gpuIdBuilder)
Map the top level scf.forall op to GPU blocks.
DiagnosedSilenceableFailure checkGpuLimits(TransformOpInterface transformOp, std::optional< int64_t > gridDimX, std::optional< int64_t > gridDimY, std::optional< int64_t > gridDimZ, std::optional< int64_t > blockDimX, std::optional< int64_t > blockDimY, std::optional< int64_t > blockDimZ)
Determine if the size of the kernel configuration is supported by the GPU architecture being used.
Definition Utils.cpp:362
DiagnosedSilenceableFailure mapNestedForallToThreadsImpl(RewriterBase &rewriter, std::optional< TransformOpInterface > transformOp, Operation *target, ArrayRef< int64_t > blockDims, int64_t warpSize, bool syncAfterDistribute)
Search scf.forall ops nested under target and map each such op to an explicit GPU implementation alon...
DiagnosedSilenceableFailure mapOneForallToThreadsImpl(RewriterBase &rewriter, std::optional< TransformOpInterface > transformOp, scf::ForallOp forallOp, ArrayRef< int64_t > blockSizes, int64_t warpSize, bool syncAfterDistribute)
Search scf.forall ops nested under target and map each such op to an explicit GPU implementation alon...
Include the generated interface declarations.
void populateGpuPromoteShuffleToAMDGPUPatterns(RewritePatternSet &patterns, std::optional< ROCDL::TargetInfo > target)
Tries to promote gpu.shuffles to specialized AMDGPU intrinsics.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
void populateGpuRewritePatterns(RewritePatternSet &patterns)
Collect all patterns to rewrite ops within the GPU dialect.
Definition Passes.h:75
void populateGpuToROCDLConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, gpu::amd::Runtime runtime, const ROCDL::TargetInfo &target)
Collect a set of patterns to convert from the GPU dialect to ROCDL.
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 configureGpuToNVVMTypeConverter(LLVMTypeConverter &converter)
Configure the LLVM type convert to convert types and address spaces from the GPU dialect to NVVM.
void populateGpuSubgroupReduceOpLoweringPattern(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate GpuSubgroupReduce pattern to NVVM.
void populateGpuToNVVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of patterns to convert from the GPU dialect to NVVM.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
std::optional< SmallVector< int64_t > > getConstantIntValues(ArrayRef< OpFoldResult > ofrs)
If all ofrs are constant integers or IntegerAttrs, return the integers.
SmallVector< Value > getValuesSortedByKey(ArrayRef< Attribute > keys, ArrayRef< Value > values, llvm::function_ref< bool(Attribute, Attribute)> compare)
Helper to sort values according to matching keys.
void populateGpuEliminateBarriersPatterns(RewritePatternSet &patterns)
Erase barriers that do not enforce conflicting memory side effects.
void populateGpuWMMAToNVVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of patterns to convert WMMA ops from GPU dialect to NVVM.
Struct to return the result of the rewrite of a forall operation.
SmallVector< Value > mappingIds
SmallVector< int64_t > mappingSizes
Builder for gpu::BlockIdOps used to map scf.forall to blocks.
Definition Utils.h:80
Helper struct for configuring the rewrite of mapped scf.forall ops to various gpu id configurations.
Definition Utils.h:59
SmallVector< DeviceMappingAttrInterface > mappingAttributes
The mapping attributes targeted by this generator.
Definition Utils.h:68
GpuIdBuilderFnType idBuilder
The constructor that builds the concrete IR for mapping ids.
Definition Utils.h:71
Builder for warp ids used to map scf.forall to reindexed threads.
Definition Utils.h:119
Builder for warp ids used to map scf.forall to reindexed warps.
Definition Utils.h:106
Builder for warpgroup ids used to map scf.forall to reindexed warpgroups.
Definition Utils.h:91
static constexpr int64_t kNumWarpsPerGroup
In the future this may be configured by the transformation.
Definition Utils.h:97
Helper type for functions that generate ids for the mapping of a scf.forall.
Definition Utils.h:30
std::string errorMsg
Error message, if not empty then building the ids failed.
Definition Utils.h:32
SmallVector< Value > predicateOps
Values used to predicate the forall body when activeMappingSizes is smaller than the available mappin...
Definition Utils.h:37
SmallVector< Value > mappingIdOps
Values used to replace the forall induction variables.
Definition Utils.h:34