92#include "llvm/ADT/STLExtras.h"
93#include "llvm/ADT/SmallPtrSet.h"
94#include "llvm/Support/Debug.h"
98#define GEN_PASS_DEF_ACCPARTITIONKERNELLOOPS
99#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
103#define DEBUG_TYPE "acc-partition-kernel-loops"
110 assert(value.
hasOneUse() &&
"expected a single use");
119 if (
auto blockArg = dyn_cast<BlockArgument>(value)) {
127 value = parWidth.getLaunchArg();
137static bool loopFullyCoveredByThreadDim(scf::ParallelOp loop,
138 ComputeRegionOp computeRegion,
140 if (parDims.size() != 1 || !parDims[0].isThreadX())
145 Value width = computeRegion.parDimToWidth(parDims[0]);
158 LoopRange orig,
Value stripIV,
164 Value newStep = arith::MulIOp::create(rewriter, loc, step, stripWidth);
165 Value bigStep = arith::MulIOp::create(rewriter, loc, stripIV, step);
166 Value newLB = arith::AddIOp::create(rewriter, loc, lb, bigStep);
167 return {newLB, orig.ub, newStep};
172static void disableRuntimeUnroll(
Operation *loop) {
177 auto unroll = LLVM::LoopUnrollAttr::get(
180 auto annotation = LLVM::LoopAnnotationAttr::get(
191static int64_t getGangChunkSize(scf::ParallelOp loop,
193 if (!llvm::any_of(parDims,
194 [](GPUParallelDimAttr dim) {
return dim.isBlockX(); }))
197 if (!chunk || *chunk <= 1)
201 bool hasReduction = loop->getNumResults() > 0;
202 loop.getBody()->walk([&](
Operation *op) {
203 if (isa<ReductionAccumulateOp, ReductionCombineOp, ReductionInitOp>(op))
210 it != loop->getBlock()->end(); ++it) {
211 if (it->getNumRegions() > 0)
213 if (isa<ReductionAccumulateOp>(*it)) {
219 LLVM_DEBUG(llvm::dbgs()
220 <<
"gang chunk size ignored: loop has reductions\n");
226class ACCPartitionKernelLoops
228 using ACCPartitionKernelLoopsBase<
229 ACCPartitionKernelLoops>::ACCPartitionKernelLoopsBase;
231 static LoopRange getLoopRange(scf::ParallelOp parOp,
int ivIdx) {
232 return {parOp.getLowerBound()[ivIdx], parOp.getUpperBound()[ivIdx],
233 parOp.getStep()[ivIdx]};
236 static void setLoopRange(
IRRewriter &rewriter, scf::ParallelOp parLoop,
237 int ivIdx, LoopRange range) {
239 parLoop.getLowerBoundMutable()[ivIdx].assign(
242 parLoop.getUpperBoundMutable()[ivIdx].assign(
246 rewriter, parLoop->getLoc(), range.step));
250 LogicalResult partitionParallelOp(
IRRewriter &rewriter,
252 ComputeRegionOp computeRegion,
253 scf::ParallelOp parallelOp);
255 void runOnOperation()
override;
258LogicalResult ACCPartitionKernelLoops::partitionParallelOp(
260 ComputeRegionOp computeRegion, scf::ParallelOp parallelOp) {
262 LLVM_DEBUG(llvm::dbgs() <<
"partitionParallelOp: " << parallelOp <<
"\n"
263 <<
"parDimsAttr: " << parDimsAttr <<
"\n");
265 if (parallelOp.getInductionVars().size() != 1) {
266 accSupport.
emitNYI(parallelOp.getLoc(),
267 "partition of an uncollapsed parallel loop");
270 if (!parDimsAttr || parDimsAttr.getArray().empty()) {
271 accSupport.
emitNYI(parallelOp.getLoc(),
272 "partition of a loop with no parallel dimension");
277 Block *parentBlock = parallelOp->getBlock();
280 GPUParallelDimAttr innerParDim = GPUParallelDimAttr::seqDim(&
getContext());
281 scf::ParallelOp seqLoop = parallelOp;
282 LoopRange newLoopRange = getLoopRange(seqLoop, 0);
284 bool loopTCEqualToBlockWidth =
285 loopFullyCoveredByThreadDim(parallelOp, computeRegion, parDims);
286 bool isStridedLoop =
false;
297 int64_t chunkSize = getGangChunkSize(seqLoop, parDims);
303 scf::ParallelOp chunkLoop =
304 scf::ParallelOp::create(rewriter, loc,
ValueRange{zero},
307 chunkLoop.getBody()->begin());
311 outerCoalescedStrip(rewriter, loc, newLoopRange,
312 chunkLoop.getInductionVars()[0], chunkWidth);
314 auto seqAttr = GPUParallelDimsAttr::get(&
getContext(), {innerParDim});
318 parallelOp = chunkLoop;
319 isStridedLoop =
true;
320 gridCoversTripCount =
false;
323 for (GPUParallelDimAttr parDim : llvm::reverse(parDims)) {
331 if (parDim.isThreadX() || parDim.isThreadY()) {
332 bool hasNestedAccumulate =
false;
333 parallelOp.getBody()->walk([&](
Operation *op) {
334 if (
auto accumulate = dyn_cast<ReductionAccumulateOp>(op)) {
335 for (GPUParallelDimAttr dim : accumulate.getParDims().getArray()) {
336 if (dim.isThreadX() || dim.isThreadY())
337 hasNestedAccumulate =
true;
340 if (isa<ReductionCombineOp, ReductionInitOp>(op)) {
343 if (
auto par = dyn_cast<scf::ParallelOp>(ancestor)) {
345 for (GPUParallelDimAttr dim : pd.getArray()) {
346 if (dim.isThreadX() || dim.isThreadY()) {
347 hasNestedAccumulate =
true;
359 if (hasNestedAccumulate) {
360 Value ub = parallelOp.getUpperBound()[0];
361 Value lb = parallelOp.getLowerBound()[0];
364 int64_t tripCount = ubConst.value() - lbConst.value();
365 for (
Value launchArg : computeRegion.getLaunchArgs()) {
366 auto parWidth = launchArg.getDefiningOp<ParWidthOp>();
367 if (!parWidth || parWidth.getParDim() != parDim)
370 if (std::optional<int64_t> width =
377 rewriter, parWidth.getLoc(), tripCount);
379 parWidth.getLaunchArgMutable().assign(clamped);
389 Value width = computeRegion.parDimToWidth(parDim);
390 scf::ParallelOp outerStripLoop = scf::ParallelOp::create(
392 isStridedLoop =
true;
393 rewriter.
moveOpBefore(parallelOp, outerStripLoop.getBody(),
394 outerStripLoop.getBody()->begin());
398 outerCoalescedStrip(rewriter, loc, newLoopRange,
399 outerStripLoop.getInductionVars()[0], width);
401 if (seqLoop->getNumResults()) {
406 std::prev(parallelOp->getBlock()->end()));
413 while (blockIter != parentBlock->
end()) {
414 if (blockIter->getNumRegions() > 0)
416 trailing.push_back(&*blockIter);
417 blockIter = std::next(blockIter);
429 if (isa<ReductionAccumulateOp>(op)) {
430 opsToMove.insert(op);
431 worklist.push_back(op);
434 while (!worklist.empty()) {
437 Operation *def = operand.getDefiningOp();
438 if (def && trailingSet.contains(def) && opsToMove.insert(def).second)
439 worklist.push_back(def);
445 if (isa<ReductionAccumulateOp>(op))
448 if (!opsToMove.contains(user)) {
449 accSupport.
emitNYI(op->getLoc(),
450 "reduction: accumulate operand is also used "
458 if (opsToMove.contains(op))
460 std::prev(parallelOp->getBlock()->end()));
465 GPUParallelDimsAttr::get(&
getContext(), {parDim}));
467 GPUParallelDimsAttr::get(&
getContext(), {innerParDim}));
468 innerParDim = parDim;
469 parallelOp = outerStripLoop;
475 if (loopTCEqualToBlockWidth)
476 newLoopRange.step = newLoopRange.ub;
477 setLoopRange(rewriter, seqLoop, 0, newLoopRange);
479 if (isStridedLoop && !loopTCEqualToBlockWidth && gridCoversTripCount)
480 disableRuntimeUnroll(seqLoop);
482 LLVM_DEBUG(llvm::dbgs() <<
"partitioned-loop: " << parallelOp);
486void ACCPartitionKernelLoops::runOnOperation() {
489 getOperation()->walk([&](ComputeRegionOp computeRegion) {
490 if (computeRegion.getRegion().getBlocks().size() > 1) {
491 accSupport.
emitNYI(computeRegion.getLoc(),
492 "multiple blocks in acc.compute_region");
497 computeRegion.getOrigin() == KernelsOp::getOperationName();
498 for (
Block &block : computeRegion.getRegion()) {
501 if (
auto parallelOp = dyn_cast<scf::ParallelOp>(op)) {
502 worklist.push_back(parallelOp);
511 for (scf::ParallelOp parallelOp : worklist) {
512 if (failed(partitionParallelOp(rewriter, accSupport, computeRegion,
Block represents an ordered list of Operations.
OpListType::iterator iterator
static BoolAttr get(MLIRContext *context, bool value)
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Operation is the basic unit of execution within MLIR.
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
operand_range getOperands()
Returns an iterator on the underlying Value's.
user_range getUsers()
Returns a range of all users.
MLIRContext * getContext()
Return the context this operation is associated with.
void moveOpBefore(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
user_range getUsers() const
bool hasOneUse() const
Returns true if this value has exactly one use.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static WalkResult advance()
static WalkResult interrupt()
InFlightDiagnostic emitNYI(Location loc, const Twine &message)
Report a case that is not yet supported by the implementation.
Specialization of arith.constant op that returns an integer of index type.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
constexpr llvm::StringLiteral getLoopAnnotationAttrName()
Canonical name used when attaching LoopAnnotationAttr as a discardable attribute on operations that d...
std::optional< int64_t > getChunkSize(Operation *op)
Return the chunk size carried by op, if any.
GPUParallelDimsAttr getParDimsAttr(Operation *op)
Obtain the parallel dimensions carried by op, if any.
mlir::Value getACCOperandForBlockArg(mlir::Value v)
If v is not a block argument of an acc.compute_region body, returns nullptr.
mlir::Value stripIndexCasts(mlir::Value value)
Follow arith.index_cast and arith.index_castui to the value being cast.
void updateParDimsAttr(Operation *op, GPUParallelDimsAttr attr)
Update parallel dimensions on op.
bool hasGridCoversTripCountAttr(Operation *op)
Return whether this loop's trip count sized its grid dimension.
void setParDimsAttr(Operation *op, GPUParallelDimsAttr attr)
Set parallel dimensions on op.
void removeGridCoversTripCountAttr(Operation *op)
Clear the record that this loop's trip count sized its grid dimension.
Include the generated interface declarations.
bool isConstantIntValue(OpFoldResult ofr, int64_t value)
Return true if ofr is constant integer equal to value.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
bool isEqualConstantIntOrValue(OpFoldResult ofr1, OpFoldResult ofr2)
Return true if ofr1 and ofr2 are the same integer constant attribute values or the same SSA value.
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.