MLIR 24.0.0git
ACCCGToGPU.cpp
Go to the documentation of this file.
1//===- ACCCGToGPU.cpp - Lower acc.compute_region to gpu.launch ------------===//
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//
9// This pass lowers `acc.compute_region` to the GPU dialect. For host-side
10// kernels it wraps the region in `gpu.launch`; for specialized acc routines
11// already inside a `gpu.func`, the body is lowered in place without emitting
12// a launch.
13//
14// Overview:
15// ---------
16// `acc.compute_region` is the compute-body representation produced after
17// OpenACC compute constructs are decomposed and parallelism has been assigned.
18// This pass is the final ACC-to-GPU lowering step for that body: it converts
19// nested `scf.parallel` / `scf.for` loops marked with `acc.par_dims` into GPU
20// block and thread parallelism, materializes privatization and reductions for
21// the device, inserts synchronization where shared state is observed across
22// threads, and erases the ACC scaffolding (`acc.compute_region`,
23// `acc.par_width`).
24//
25// Transformations:
26// ----------------
27// 1. Launch creation: outside a `gpu.func`, each `acc.compute_region` becomes a
28// `gpu.launch` whose grid and block sizes come from `acc.par_width` launch
29// operands (defaulting to 1). Kernel/module name attributes are preserved.
30// Inside a `gpu.func` (specialized acc routine), no launch is emitted.
31//
32// 2. Parallel loops: `scf.parallel` with a single `acc.par_dims` entry is
33// mapped to the corresponding GPU dimension (`block_*` or `thread_*`).
34// Sequential dimensions remain as `scf.parallel`/`scf.for` loops in the
35// generated kernel body.
36//
37// 3. Privatization: `acc.privatize` / `acc.private_local` storage is
38// materialized as one of: a per-thread `memref.alloca` (thread-private
39// arrays within the stack budget), an `acc.gpu_shared_memory` buffer
40// (gang-/worker-private arrays that fit the shared-memory budget), or a
41// `memref.alloc` whose pointer is broadcast to the block through a small
42// shared-memory slot (the data lives in global memory; shared memory only
43// holds the broadcast pointer).
44//
45// 4. Predication: `acc.predicate_region` becomes `scf.if` guarded by active
46// thread/block indices derived from `acc.par_dims` and launch dimensions.
47//
48// 5. Reductions: `acc.reduction_*` ops are lowered to GPU reduction and
49// synchronization primitives according to each reduction's parallel
50// dimensions and accumulator storage class.
51//
52// Example:
53// --------
54// Before:
55// %c128 = arith.constant 128 : index
56// %tx = acc.par_width %c128 par_dim(#acc.par_dim<thread_x>)
57// acc.compute_region launch(%arg0 = %tx) {
58// %c0 = arith.constant 0 : index
59// %c1 = arith.constant 1 : index
60// scf.parallel (%iv) = (%c0) to (%c128) step (%c1) {
61// ...
62// scf.reduce
63// } {acc.par_dims = #acc<par_dims[thread_x]>}
64// acc.yield
65// } <{origin = "acc.parallel"}>
66//
67// After:
68// gpu.launch blocks(%bidx, %bidy, %bidz) in (%gdimx = %c1, ...)
69// threads(%tidx, %tidy, %tidz) in (%bdimx = %c128, ...) {
70// ...
71// }
72//
73// Requirements:
74// -------------
75// - Must run on a GPU device type (`device-type` option); host and multicore
76// targets are rejected.
77// - Input must already be in the `acc.compute_region` form: nested SCF loops
78// carry `acc.par_dims`, privatization is expressed via `acc.privatize` /
79// `acc.private_local`, and reductions use the `acc.reduction_*` ops.
80// - Each `scf.parallel` processed by this pass is expected to have exactly
81// one parallel dimension and one induction variable.
82// - For acc routines, the `acc.compute_region` must live inside a `gpu.func`
83// in the GPU module.
84// - Uses `acc::OpenACCSupport` for NYI reporting and compiler remarks.
85// - Pass options: `max-workgroup-shared-memory`, `max-thread-private-stack`,
86// and `subgroup-size` (used for reductions and block-dimension alignment).
87//
88//===----------------------------------------------------------------------===//
89
92
110#include "mlir/IR/Block.h"
112#include "mlir/IR/BuiltinTypes.h"
113#include "mlir/IR/Diagnostics.h"
114#include "mlir/IR/Dominance.h"
115#include "mlir/IR/IRMapping.h"
116#include "mlir/IR/OpDefinition.h"
117#include "mlir/IR/PatternMatch.h"
118#include "mlir/IR/SymbolTable.h"
119#include "mlir/IR/Value.h"
123#include "mlir/Support/LLVM.h"
125#include "llvm/ADT/ArrayRef.h"
126#include "llvm/ADT/DenseMap.h"
127#include "llvm/ADT/STLExtras.h"
128#include "llvm/ADT/StringExtras.h"
129#include "llvm/ADT/Twine.h"
130#include "llvm/Support/Debug.h"
131#include <algorithm>
132#include <optional>
133#include <utility>
134
135namespace mlir {
136namespace acc {
137#define GEN_PASS_DEF_ACCCGTOGPU
138#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
139} // namespace acc
140} // namespace mlir
141
142#define DEBUG_TYPE "acc-cg-to-gpu"
143
144namespace {
145using namespace mlir;
146using namespace mlir::acc;
147
148enum class PrivateMemScope { Thread, Worker, Gang, None };
149
150/// Device label used in compiler remarks (e.g. "NVIDIA GPU").
151static std::string getDeviceRemarkQualifier(DeviceType deviceType) {
152 switch (deviceType) {
153 case DeviceType::None:
154 case DeviceType::Star:
155 case DeviceType::Default:
156 return "GPU";
157 default: {
158 std::string name;
159 llvm::StringRef deviceName = stringifyDeviceType(deviceType);
160 name.reserve(deviceName.size());
161 for (char c : deviceName)
162 name.push_back(llvm::toUpper(c));
163 return name + " GPU";
168/// True when \p op is inside a specialized acc routine function.
170 FunctionOpInterface funcOp = op->getParentOfType<FunctionOpInterface>();
171 return funcOp && acc::isSpecializedAccRoutine(funcOp);
173
174/// Maps an acc.routine's parallelism clauses to a GPU parallel dimension.
175static GPUParallelDimAttr
176getAccRoutineParDim(RoutineOp routineOp, MLIRContext *ctx,
177 const ACCToGPUMappingPolicy &policy) {
178 if (routineOp.getGangDimValue() ||
179 routineOp.getGangDimValue(DeviceType::Nvidia)) {
180 int64_t gangDimValue = routineOp.getGangDimValue(DeviceType::Nvidia)
181 ? *routineOp.getGangDimValue(DeviceType::Nvidia)
182 : *routineOp.getGangDimValue();
183 ParLevel gangLevel = getGangParLevel(gangDimValue);
184 return policy.gangDim(ctx, gangLevel);
185 }
186 if (routineOp.hasGang() || routineOp.hasGang(DeviceType::Nvidia))
187 return policy.gangDim(ctx, ParLevel::gang_dim1);
188 if (routineOp.hasWorker() || routineOp.hasWorker(DeviceType::Nvidia))
189 return policy.workerDim(ctx);
190 if (routineOp.hasVector() || routineOp.hasVector(DeviceType::Nvidia))
191 return policy.vectorDim(ctx);
192 return policy.seqDim(ctx);
193}
194
195/// Looks up the acc.routine symbol associated with \p funcOp.
196static RoutineOp getRoutineOpForAccRoutineFunction(FunctionOpInterface funcOp,
197 const SymbolTable &symTab) {
198 if (isSpecializedAccRoutine(funcOp)) {
199 SpecializedRoutineAttr attr =
200 funcOp->getDiscardableAttrOfType<SpecializedRoutineAttr>(
202 return symTab.lookup<RoutineOp>(attr.getRoutine().getLeafReference());
203 }
204 RoutineInfoAttr routineInfo =
205 funcOp->getDiscardableAttrOfType<RoutineInfoAttr>(
207 if (!routineInfo || routineInfo.getAccRoutines().empty())
208 return nullptr;
209 return symTab.lookup<RoutineOp>(
210 routineInfo.getAccRoutines().front().getLeafReference());
211}
212
213/// Returns the parallelism level of a specialized acc routine function.
214static GPUParallelDimAttr
215getSpecializedRoutineDim(FunctionOpInterface funcOp,
216 const ACCToGPUMappingPolicy &policy) {
217 SpecializedRoutineAttr specAttr =
218 funcOp->getDiscardableAttrOfType<SpecializedRoutineAttr>(
220 assert(specAttr && "expected specialized routine attribute");
221 return policy.map(funcOp->getContext(), specAttr.getLevel().getValue());
222}
223
224/// Returns the parallelism dimension of a callee acc routine, if any.
225static GPUParallelDimAttr
226getAccRoutineCallParDim(CallOpInterface callOp,
227 const ACCToGPUMappingPolicy &policy) {
228 std::optional<CallInterfaceCallable> callee = callOp.getCallableForCallee();
229 if (!callee)
230 return nullptr;
231 SymbolRefAttr calleeSymbolRef = dyn_cast<SymbolRefAttr>(*callee);
232 if (!calleeSymbolRef)
233 return nullptr;
234 ModuleOp moduleOp = callOp->getParentOfType<ModuleOp>();
235 if (!moduleOp)
236 return nullptr;
237
238 SymbolTable symTab(moduleOp);
239 FunctionOpInterface funcOp =
240 symTab.lookup<FunctionOpInterface>(calleeSymbolRef.getLeafReference());
241 if (!funcOp)
242 return nullptr;
244 if (isSpecializedAccRoutine(funcOp))
245 return getSpecializedRoutineDim(funcOp, policy);
246 if (RoutineOp routineOp = getRoutineOpForAccRoutineFunction(funcOp, symTab))
247 return getAccRoutineParDim(routineOp, funcOp.getContext(), policy);
248 return nullptr;
249}
250
251/// Collects parallel dimensions from enclosing loops and the compute region.
252static SmallVector<GPUParallelDimAttr> getAncestorParDims(Operation *op) {
254 ComputeRegionOp computeRegion = op->getParentOfType<ComputeRegionOp>();
255 assert(computeRegion && "missing enclosing acc.compute_region");
256 scf::ParallelOp parentLoop = op->getParentOfType<scf::ParallelOp>();
257 // True while parentLoop is the innermost parallel ancestor of op.
258 bool isInnermostParallelParent = true;
259 while (parentLoop) {
260 bool hasNonSeqParDim = false;
261 if (GPUParallelDimsAttr parDimsAttr = getParDimsAttr(parentLoop)) {
262 for (GPUParallelDimAttr parDim : parDimsAttr.getArray()) {
263 insertParDim(parDimsArray, parDim);
264 if (!parDim.isSeq())
265 hasNonSeqParDim = true;
266 }
267 }
268 // Include launch dims for a block-redundant ancestor when:
269 // - it is itself worksharing (e.g. vector + gpu_block_redundant), or
270 // - it is the innermost parallel parent (sequential remnant after
271 // partition-kernel-loops), so the body is not predicated on blockIdx.
272 // Do not include them for an outer sequential block-redundant wrapper
273 // around nested gang/worker/vector worksharing: that widens gang-private
274 // storage to per-thread.
275 if (hasGPUBlockRedundantAttr(parentLoop) &&
276 (hasNonSeqParDim || isInnermostParallelParent))
277 for (GPUParallelDimAttr parDim : computeRegion.getLaunchParDims())
278 insertParDim(parDimsArray, parDim);
279 isInnermostParallelParent = false;
280 parentLoop = parentLoop->getParentOfType<scf::ParallelOp>();
281 }
282
283 if (GPUParallelDimsAttr parDimsAttr = getParDimsAttr(computeRegion))
284 for (GPUParallelDimAttr parDim : parDimsAttr.getArray())
285 insertParDim(parDimsArray, parDim);
286 return parDimsArray;
287}
288
289/// Strips index casts to reach the underlying defining value.
290static Value stripIndexCastsFromValue(Value x) {
291 Operation *op = x.getDefiningOp();
292 if (!op)
293 return x;
294 while (arith::IndexCastOp castOp = dyn_cast<arith::IndexCastOp>(op)) {
295 op = castOp->getOperand(0).getDefiningOp();
296 if (!op)
297 return x;
298 }
299 return op->getResult(0);
300}
301
302/// Extracts a compile-time integer constant from \p x, when known.
303static FailureOr<int64_t> extractIntConst(Value x,
304 bool stripIndexCasts = false) {
305 if (stripIndexCasts)
306 x = stripIndexCastsFromValue(x);
307 Operation *op = x.getDefiningOp();
308 if (op) {
309 if (arith::ConstantIntOp constOp = dyn_cast<arith::ConstantIntOp>(op)) {
310 assert(constOp.getType().getIntOrFloatBitWidth() <= 64);
311 return constOp.value();
312 }
313 if (arith::ConstantIndexOp constOp = dyn_cast<arith::ConstantIndexOp>(op))
314 return constOp.value();
315 }
316 return failure();
317}
318
319/// True when \p x is a constant equal to \p y (modulo index casts).
320static bool sameEffectiveValue(Value x, int64_t y) {
321 x = stripIndexCastsFromValue(x);
322 FailureOr<int64_t> conX = extractIntConst(x);
323 if (failed(conX))
324 return false;
325 return *conX == y;
326}
327
328/// Continues tracking a memref through view-like and partial-access ops.
329static bool getPassThroughResults(Operation *userOp, Value trackedOperand,
330 SmallVectorImpl<Value> &passThroughResults) {
331 if (ViewLikeOpInterface viewLikeOp = dyn_cast<ViewLikeOpInterface>(userOp)) {
332 if (viewLikeOp.getViewSource() == trackedOperand) {
333 passThroughResults.push_back(viewLikeOp.getViewDest());
334 return true;
335 }
336 return false;
337 }
338
339 // Partial-entity accesses (e.g. array element or field access) forward the
340 // base entity through to their results, so treat them as pass-through when
341 // the base entity is the value being tracked.
342 if (acc::PartialEntityAccessOpInterface partialAccess =
343 dyn_cast<acc::PartialEntityAccessOpInterface>(userOp)) {
344 if (partialAccess.getBaseEntity() == trackedOperand) {
345 passThroughResults.append(userOp->result_begin(), userOp->result_end());
346 return true;
347 }
348 return false;
349 }
350 return false;
351}
352
353/// Skips memref view/cast chains to reach the underlying buffer.
354static Value unwrapMemRefConversion(Value v) {
355 while (Operation *op = v.getDefiningOp()) {
356 if (ViewLikeOpInterface viewLike = dyn_cast<ViewLikeOpInterface>(op)) {
357 if (isa<MemRefType>(viewLike.getViewSource().getType()) ||
358 isa<MemRefType>(viewLike.getViewDest().getType())) {
359 v = viewLike.getViewSource();
360 continue;
361 }
362 }
363 break;
364 }
365 return v;
366}
367
368/// Appends to \p sources the operands of \p def that the storage a result of
369/// \p def refers to is derived from. Scalar operands (extents, strides,
370/// offsets, indices) only describe the shape of the access, never where the
371/// storage lives, so they are not followed: an extent loaded from one private
372/// descriptor must not make a view of another private buffer look like it is
373/// backed by that descriptor.
374static void getStorageSourceOperands(Operation *def,
375 SmallVectorImpl<Value> &sources) {
376 if (ViewLikeOpInterface viewLike = dyn_cast<ViewLikeOpInterface>(def)) {
377 sources.push_back(viewLike.getViewSource());
378 return;
379 }
380 if (acc::PartialEntityAccessOpInterface partialAccess =
381 dyn_cast<acc::PartialEntityAccessOpInterface>(def)) {
382 if (Value base = partialAccess.getBaseEntity())
383 sources.push_back(base);
384 return;
385 }
386 for (Value operand : def->getOperands())
387 if (!isa<IntegerType, IndexType, FloatType, ComplexType>(operand.getType()))
388 sources.push_back(operand);
389}
390
391/// Walks back from a memref use to its defining `acc.private_local`, if any,
392/// looking through view/cast ops.
393static acc::PrivateLocalOp getPrivateLocalForMemref(Value memref);
394
395/// Returns the dimensions that own \p privateLocal.
396static GPUParallelDimsAttr
397getPrivateParDims(acc::PrivateLocalOp privateLocal,
398 acc::ComputeRegionOp computeRegion);
399
400/// True when the storage backing \p privateLocal is thread_x-private. An
401/// unknown scope conservatively counts as per-thread.
402static bool storageHasThreadX(acc::PrivateLocalOp privateLocal,
403 acc::ComputeRegionOp computeRegion) {
404 GPUParallelDimsAttr dims = getPrivateParDims(privateLocal, computeRegion);
405 return !dims || llvm::any_of(dims.getArray(), [](GPUParallelDimAttr d) {
406 return d.isThreadX();
407 });
408}
409
410/// Returns the sole user of \p v, or null if it has zero or multiple uses.
411static Operation *getOnlyUser(Value v) {
412 if (!v.hasOneUse())
413 return nullptr;
414 return *v.user_begin();
415}
416
417/// True when \p privatize is privatized at thread_x parallelism.
418static bool isThreadXPrivatize(PrivatizeOp privatize) {
419 if (GPUParallelDimsAttr parDimsAttr = privatize.getParDimsAttr())
420 return llvm::any_of(parDimsAttr.getArray(),
421 [](GPUParallelDimAttr d) { return d.isThreadX(); });
422 return false;
423}
424
425/// True when \p block is nested in a region that only part of the workgroup
426/// enters.
427static bool isInsideConditional(Block *block) {
428 if (!block)
429 return false;
430 for (Operation *parent = block->getParentOp();
431 parent && !isa<gpu::LaunchOp, FunctionOpInterface>(parent);
432 parent = parent->getParentOp())
433 if (isa<RegionBranchOpInterface>(parent) &&
434 !isa<LoopLikeOpInterface, scf::ExecuteRegionOp>(parent))
435 return true;
436 return false;
437}
438
439/// Emits a workgroup-wide GPU barrier.
440static void emitGPUBarrierWorkgroup(OpBuilder &builder, Location loc) {
441 gpu::BarrierOp::create(builder, loc);
442}
443
444/// Emits a subgroup-scoped GPU barrier.
445static void emitGPUBarrierSubgroup(OpBuilder &builder, Location loc) {
446 gpu::BarrierOp::create(builder, loc, /*address_spaces=*/ArrayAttr{},
447 /*named_barrier=*/Value{},
448 gpu::BarrierScope::Subgroup);
449}
450
451/// Emits a barrier over the lanes of this thread's ThreadY row. \p rowWidth
452/// (blockDim.x) must divide \p subgroupSize so the rows tile a subgroup. A
453/// subgroup-wide barrier would also tie together the other rows sharing it.
454static void emitGPUBarrierRow(OpBuilder &builder, Location loc,
455 int64_t rowWidth, int64_t subgroupSize) {
456 assert(rowWidth > 0 && subgroupSize % rowWidth == 0 &&
457 "row must tile the subgroup");
458 Type i32Ty = builder.getI32Type();
459 int64_t rowsPerSubgroup = subgroupSize / rowWidth;
460
461 // laneBase = (tid.y % rowsPerSubgroup) * rowWidth. Both operands are powers
462 // of two here, since rowWidth divides the subgroup size.
463 Value threadY = gpu::ThreadIdOp::create(builder, loc, builder.getIndexType(),
464 gpu::Dimension::y);
465 Value threadY32 = arith::IndexCastOp::create(builder, loc, i32Ty, threadY);
466 Value rowMask =
467 arith::ConstantIntOp::create(builder, loc, i32Ty, rowsPerSubgroup - 1);
468 Value rowIndex = arith::AndIOp::create(builder, loc, threadY32, rowMask);
469 Value width = arith::ConstantIntOp::create(builder, loc, i32Ty, rowWidth);
470 Value laneBase = arith::MulIOp::create(builder, loc, rowIndex, width);
471
472 Value laneBits = arith::ConstantIntOp::create(builder, loc, i32Ty,
473 (int64_t{1} << rowWidth) - 1);
474 Value mask = arith::ShLIOp::create(builder, loc, laneBits, laneBase);
475 NVVM::SyncWarpOp::create(builder, loc, mask);
476}
477
478/// The storage that a set of memory accesses refers to, identified by the value
479/// that names it (see getStorageRoot). \c unknown is set when an access refers
480/// to storage that could not be identified, which then may alias anything.
481struct SharedStorage {
482 llvm::SmallPtrSet<Value, 8> roots;
483 bool unknown = false;
484
485 bool empty() const { return roots.empty() && !unknown; }
486 void insert(const SharedStorage &other) {
487 roots.insert(other.roots.begin(), other.roots.end());
488 unknown |= other.unknown;
489 }
490};
491
492/// Lowers a single `acc.compute_region` to GPU dialect IR.
493class ACCCGToGPULowering {
494public:
495 explicit ACCCGToGPULowering(acc::ComputeRegionOp computeRegion,
496 RewriterBase &rewriter,
497 acc::OpenACCSupport &accSupport,
498 const ACCCGToGPUOptions &options)
499 : rewriter(rewriter), computeRegion(computeRegion),
500 accSupport(accSupport), options(options),
501 sharedMemBudget(
502 options.maxWorkgroupSharedMemory,
503 sumExistingSharedMemoryBytes(computeRegion.getRegion())) {}
504
505 /// Main entry point: emit launch (if needed) and lower the region body.
506 LogicalResult rewrite();
507
508 gpu::LaunchOp getLaunch() const { return launch; }
509
510 bool hasFailed = false;
511 bool insideAccumulateGridStride = false;
512 Value reductionSharedBuf;
513 // Reduction-accumulator slot (memref) -> the block-reduced value stored into
514 // it; lets a block combine use the register instead of reloading.
515 llvm::DenseMap<Value, Value> reductionAccumValue;
516 // Combine reloads recorded before accumulates are lowered, patched up after.
517 llvm::SmallVector<std::pair<Value, memref::LoadOp>> pendingCombineReloads;
518
519private:
520 /// Lower a parallel loop to the GPU dimension given by its `acc.par_dims`.
521 void processParallelOp(scf::ParallelOp parallelOp);
522 /// Lower a sequential loop, including any required post-loop barriers.
523 template <typename LoopOp>
524 void processSeqLoop(LoopOp loopOp);
525 /// Lower an `acc.predicate_region` to a predicated `scf.if`.
526 void processPredicateRegion(acc::PredicateRegionOp interOp);
527 /// Materialize storage for an `acc.private_local`.
528 void
529 processPrivateLocal(acc::PrivateLocalOp privateLocal,
530 std::optional<int64_t> sharedMemCopies = std::nullopt);
531 /// Lower an `acc.privatize` to device storage.
532 Value processPrivatize(acc::PrivatizeOp privatize);
533 /// Heap-allocate privatize storage and insert a matching dealloc.
534 Value allocatePrivatizeHeapStorage(acc::PrivatizeOp privatize,
535 MemRefType baseTy,
536 ValueRange mappedDynamicSizes);
537 /// Clone and lower an `scf.execute_region`.
538 void processExecuteRegion(scf::ExecuteRegionOp op);
539 /// Lower `acc.reduction_accumulate`.
540 void processAccumulateOp(acc::ReductionAccumulateOp op);
541 /// Lower `acc.reduction_accumulate_array`.
542 void processAccumulateArrayOp(acc::ReductionAccumulateArrayOp op);
543 /// Lower `acc.reduction_init`.
544 void processReductionOp(acc::ReductionInitOp op);
545 /// Lower `acc.reduction_combine`.
546 void processReductionCombineOp(acc::ReductionCombineOp op);
547 /// Lower `acc.reduction_combine_region`.
548 void processCombineRegionOp(acc::ReductionCombineRegionOp op);
549 /// Clone a leaf operation into the lowered region.
550 void processGenericOp(Operation *op);
551 /// Clone and recursively lower an operation with nested regions.
552 void processGenericOpWithRegions(Operation *op);
553 /// Dispatch lowering for one operation in the compute-region body.
554 void processOp(Operation *op);
555
556 /// Emit an atomic reduction update to \p memref.
557 void constructAtomicAccumulation(Location loc, Value memref,
558 ValueRange indices, Value input,
559 arith::AtomicRMWKind kind);
560
561 /// Map an ACC reduction operator to an atomic RMW kind.
562 FailureOr<arith::AtomicRMWKind> getReductionKind(acc::ReductionOperator redOp,
563 Type type, Location loc);
564
565 /// Split launch dimensions into those that execute \p op and those that do
566 /// not, for predication and barrier placement.
567 std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
568 SmallVector<mlir::acc::GPUParallelDimAttr>>
569 computeActiveAndInactiveParDims(Operation *op, Block *block);
570
571 /// Build a predicate that is true only on inactive parallel dimensions.
572 Value
573 emitPredicate(Location loc,
574 SmallVector<mlir::acc::GPUParallelDimAttr> &inactiveParDims);
575
576 /// True when \p privateLocal may be placed in shared memory; returns the
577 /// number of copies needed, or nullopt if ineligible.
578 std::optional<int64_t>
579 isEligibleForSharedMemory(acc::PrivateLocalOp privateLocal,
580 MemRefType baseTy);
581
582 /// Reserve \p bytes from the shared-memory budget.
583 bool tryAllocateSharedMemory(int64_t bytes);
584
585 /// Record \p privateLocal as given per-thread storage, for the closing
586 /// remark. Whether that storage lands in registers or in local memory is
587 /// decided later, so the remark reports the allocation, not the placement.
588 /// Privates with no recoverable name or compiler temps are skipped.
589 void recordThreadPrivate(acc::PrivateLocalOp privateLocal);
590
591 /// Record \p privatizeOp as global memory storage, for the closing remark.
592 void recordGlobalMemory(acc::PrivatizeOp privatizeOp);
593
594 /// Element size in bytes for \p elementType .
595 int64_t getElementSizeInBytes(Location loc, Type elementType) const;
596
597 /// True when a static privatization fits in the per-thread stack budget.
598 bool canUseStackAlloca(MemRefType baseTy, Location loc,
599 int64_t maxThreadPrivateStack) const;
600
601 /// Emit a barrier scoped to the parallel dimensions in \p parDimsAttr.
602 void createBarrier(Location loc, mlir::acc::GPUParallelDimsAttr parDimsAttr);
603
604 /// Emit a per-row (per-worker) barrier.
605 /// Runtime branch on blockDim.y == 1 (workgroup-wide); compile-time choice
606 /// between gpu.barrier scope<subgroup> (staticBlockDimX <= subgroupSize)
607 /// and a named gpu.barrier (staticBlockDimX > subgroupSize) with tid.y+1.
608 void createPerRowBarrier(Location loc);
609
610 /// Insert barriers after a sequential loop when shared private state must be
611 /// visible to later loops.
612 void createBarrierAfterSeqLoop(Operation *loopOp);
613
614 /// Flush any deferred post-loop barriers that precede \p beforeOp.
615 void flushDeferredBarriersBefore(Operation *beforeOp);
616
617 /// True when \p loopOp may write shared memory read by a later sibling loop.
618 bool mayWriteSharedMemory(Operation *loopOp);
619
620 /// True when the thread-partitioned loop \p loop runs inside a sequential
621 /// loop nest, writes memory that more than one thread of its row or block
622 /// can see, and is followed (in the same or a later iteration of the nest)
623 /// by code that may read that memory. The sequential nest is executed by
624 /// every thread, so those readers can run before the threads that execute
625 /// the loop iterations have stored their results unless the loop is followed
626 /// by a barrier.
627 bool needsBarrierAfterThreadLoop(scf::ParallelOp loop);
628
629 /// True when \p root may read (\p reads) or write (\p writes) memory that is
630 /// not private to a single thread. Storage allocated inside \p localScope is
631 /// private to it. With \p workerLevel, worker-private storage also counts as
632 /// private, because the lanes of a worker-partitioned loop do not share it
633 /// with other workers. Operations inside \p ignore are skipped. When
634 /// \p collect is given, the walk does not stop at the first access and
635 /// records the storage of every shared access in it. When \p filter is given,
636 /// accesses to storage known to differ from the storage in \p filter are
637 /// ignored.
638 bool mayAccessSharedMemory(Operation *root, bool reads, bool writes,
639 bool workerLevel, Operation *localScope,
640 Operation *ignore = nullptr,
641 SharedStorage *collect = nullptr,
642 const SharedStorage *filter = nullptr);
643
644 /// Parallelism scope (thread, worker, or gang) of a privatized variable.
645 PrivateMemScope getPrivateMemScope(acc::PrivatizeOp privatizeOp);
646
647 /// Parallelism scope of the private buffer backing \p memref.
648 PrivateMemScope getPrivateScopeForMemref(Value memref);
649
650 /// `acc.privatize` that materialized the private buffer for \p memref.
651 acc::PrivatizeOp getPrivatizeForMemref(Value memref);
652
653 /// Collect privatize ops of the shared private buffers stored to under \p
654 /// root, keeping the gang- and worker-private ones apart: the two scopes need
655 /// different barriers, so a store at one scope must not stand in for the
656 /// other.
657 void collectSharedPrivateStores(
658 Operation *root, llvm::SmallPtrSetImpl<Operation *> &gangPrivatizes,
659 llvm::SmallPtrSetImpl<Operation *> &workerPrivatizes);
660
661 /// True when \p memref is backed by one of \p storePrivatizes at \p
662 /// storeScope.
663 bool isMatchingPrivateMemref(
664 Value memref, PrivateMemScope storeScope,
665 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes);
666
667 /// True when a parallel region under \p seqLoopOp, outside \p skipOp, uses a
668 /// private buffer at \p storeScope backed by one of \p storePrivatizes.
669 bool hasParallelPrivateReuse(
670 LoopLikeOpInterface seqLoopOp, Operation *skipOp,
671 PrivateMemScope storeScope,
672 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes);
673
674 /// Whether a predicate region needs a barrier before stores that will be read
675 /// by a later parallel loop over the same private memory.
676 PrivateMemScope needsPreStoreReuseBarrier(acc::PredicateRegionOp interOp);
677
678 /// Whether \p loopOp needs a barrier at the top of its body because a
679 /// gang-private slot it writes is reused by the next iteration.
680 bool needsInLoopReuseBarrier(Operation *loopOp);
681
682 /// Emit `gpu.all_reduce` for a reduction partial.
683 void createGPUAllReduceOp(Location loc, Value input, Value memref,
684 arith::AtomicRMWKind kind,
685 mlir::acc::GPUParallelDimsAttr parDimsAttr,
686 ValueRange indices = {},
687 bool isPerThreadPrivateTarget = false);
688
689 /// Finish lowering a deferred `acc.reduction_accumulate`.
690 void postprocessAccumulateOp(acc::ReductionAccumulateOp op);
691
692 /// Finish lowering reductions attached to a parallel loop.
693 void postprocessLoopReduction(scf::ParallelOp parLoop);
694
695 /// Populate block/thread id and grid/block dimension maps for device
696 /// routines.
697 static void
698 createForAllDimensions(RewriterBase &rewriter, Location loc,
699 llvm::DenseMap<gpu::Processor, Value> &ids,
700 llvm::DenseMap<gpu::Processor, Value> &dims) {
701 ids[gpu::Processor::BlockX] = gpu::BlockIdOp::create(
702 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
703 ids[gpu::Processor::BlockY] = gpu::BlockIdOp::create(
704 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::y);
705 ids[gpu::Processor::BlockZ] = gpu::BlockIdOp::create(
706 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::z);
707 ids[gpu::Processor::ThreadX] = gpu::ThreadIdOp::create(
708 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
709 ids[gpu::Processor::ThreadY] = gpu::ThreadIdOp::create(
710 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::y);
711 ids[gpu::Processor::ThreadZ] = gpu::ThreadIdOp::create(
712 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::z);
713 dims[gpu::Processor::BlockX] = gpu::GridDimOp::create(
714 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
715 dims[gpu::Processor::BlockY] = gpu::GridDimOp::create(
716 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::y);
717 dims[gpu::Processor::BlockZ] = gpu::GridDimOp::create(
718 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::z);
719 dims[gpu::Processor::ThreadX] = gpu::BlockDimOp::create(
720 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
721 dims[gpu::Processor::ThreadY] = gpu::BlockDimOp::create(
722 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::y);
723 dims[gpu::Processor::ThreadZ] = gpu::BlockDimOp::create(
724 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::z);
725 }
726
727 /// Return the compute-region block argument for \p outside, adding an `ins`
728 /// operand when needed.
729 BlockArgument getOrAppendInsBlockArg(Value outside) {
730 if (std::optional<BlockArgument> blockArg =
731 computeRegion.getBlockArg(outside)) {
732 return *blockArg;
733 }
734 return computeRegion.appendInputArg(outside);
735 }
736
737 /// Wire dynamic privatization extents into the compute region as `ins` args.
738 void preparePrivatizeExtentInsOperands() {
739 computeRegion.walk([&](acc::PrivateLocalOp privateLocal) {
740 acc::PrivatizeOp privatizeOp =
741 getPrivatizeOp(privateLocal, computeRegion);
742 if (privatizeOp->getParentOfType<acc::ComputeRegionOp>() == computeRegion)
743 return;
744 for (Value extent : privatizeOp.getDynamicSizes())
745 getOrAppendInsBlockArg(extent);
746 });
747 }
748
749 /// Resolve dynamic size operands for a privatized array.
750 SmallVector<Value>
751 resolvePrivateLocalDynamicExtents(acc::PrivateLocalOp privateLocal) {
752 acc::PrivatizeOp privatizeOp = getPrivatizeOp(privateLocal, computeRegion);
753 SmallVector<Value> extents;
754 for (Value extent : privatizeOp.getDynamicSizes()) {
755 if (std::optional<BlockArgument> blockArg =
756 computeRegion.getBlockArg(extent)) {
757 extents.push_back(mapping.lookupOrDefault(*blockArg));
758 continue;
759 }
760 extents.push_back(mapping.lookupOrDefault(extent));
761 }
762 return extents;
763 }
764
765 RewriterBase &rewriter;
766 acc::ComputeRegionOp computeRegion;
767
768 acc::OpenACCSupport &accSupport;
769 const ACCCGToGPUOptions &options;
770 gpu::LaunchOp launch;
771 IRMapping mapping;
772 llvm::SmallVector<scf::ParallelOp> loopReductions;
773 llvm::DenseMap<gpu::Processor, Value> threadIdMap;
774 llvm::DenseMap<gpu::Processor, Value> dimensionMap;
775 // True if ThreadY reduction exists, which triggers subgroup alignment
776 bool hasThreadYReduction = false;
777 // True if a ThreadX reduction exists, whose shuffles stay inside a row
778 bool hasThreadXReduction = false;
779 // True if an array reduction spans any thread dimension
780 bool hasThreadLevelArrayReduction = false;
781 // The acc.private_local backing each array reduction whose partials are
782 // combined across a thread dimension, mapped to its accumulate.
783 llvm::DenseMap<Operation *, acc::ReductionAccumulateArrayOp>
784 threadArrayAccumulators;
785 // True if any ThreadX routine call exists in the kernel
786 bool hasThreadLevelRoutineCall = false;
787 // True when a per-row ThreadY barrier is emitted
788 bool hasThreadYBarrier = false;
789
790 // Reusable privatize broadcast slots per type; disabled for kernels.
791 llvm::DenseMap<Type, Value> privatizeBroadcastCache;
792
793 int64_t staticBlockDimX = 1024;
794 int64_t staticBlockDimY = 1024;
795 int64_t staticBlockDimZ = 1024;
796
797 /// True when the launch is (1, N, 1) with 1 < N <= subgroupSize, so every
798 /// worker owns one thread. N is capped by the worker-indexed shared buffers,
799 /// which hold subgroupSize entries.
800 bool isSingleThreadWorkerLaunch() const {
801 return staticBlockDimX == 1 && staticBlockDimZ == 1 &&
802 staticBlockDimY > 1 && staticBlockDimY <= options.subgroupSize;
803 }
804
805 /// True when only worker reductions would need the rows aligned. They combine
806 /// their partials in the lowest N threads of the block, not within a row, so
807 /// a row may sit anywhere in a subgroup. Array accumulates use atomics
808 /// instead and still need alignment.
809 bool isWorkerOnlyShuffleLaunch() const {
810 return hasThreadYReduction && !hasThreadXReduction &&
811 !hasThreadLevelArrayReduction && staticBlockDimZ == 1 &&
812 staticBlockDimY > 1 && staticBlockDimY <= options.subgroupSize &&
813 options.subgroupSize % staticBlockDimX == 0;
814 }
815
816 acc::DefaultACCToGPUMappingPolicy defaultPolicy;
817 SharedMemoryBudget sharedMemBudget;
818 SmallVector<std::string> sharedMemPrivateVarNames;
819 SmallVector<std::string> threadPrivateVarNames;
820 SmallVector<std::string> globalMemVarNames;
821 llvm::SmallVector<Operation *, 4> deferredBarrierSeqLoops;
822
823 Value getThreadId(Location loc, gpu::Dimension dim) {
824 return gpu::ThreadIdOp::create(rewriter, loc, rewriter.getIndexType(), dim);
825 }
826
827 Value getBlockDim(Location loc, gpu::Dimension dim) {
828 return gpu::BlockDimOp::create(rewriter, loc, rewriter.getIndexType(), dim);
829 }
830
831 /// Thread id for \p proc, from the launch op or the routine context map.
832 Value getGPUThreadIdFor(gpu::Processor proc) {
833 return getGPUThreadId(proc, getLaunch(), threadIdMap);
834 }
835
836 /// Grid/block dimension for \p proc, from the launch op or routine map.
837 Value getGPUSizeFor(gpu::Processor proc) {
838 return getGPUSize(proc, getLaunch(), dimensionMap);
839 }
840};
841
842int64_t ACCCGToGPULowering::getElementSizeInBytes(Location loc,
843 Type elementType) const {
844 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
845 if (std::optional<acc::TypeSizeAndAlignment> sizeAndAlignment =
846 accSupport.getTypeSizeAndAlignment(elementType, module)) {
847 return sizeAndAlignment->first.getFixedValue();
848 }
849 std::string msg;
850 llvm::raw_string_ostream os(msg);
851 os << "element size computation for unsupported type: " << elementType;
852 (void)accSupport.emitNYI(loc, os.str());
853 return 0;
854}
855
856bool ACCCGToGPULowering::canUseStackAlloca(
857 MemRefType baseTy, Location loc, int64_t maxThreadPrivateStack) const {
858 for (int64_t dim : baseTy.getShape())
859 if (dim == ShapedType::kDynamic)
860 return false;
861 int64_t elementSize = getElementSizeInBytes(loc, baseTy.getElementType());
862 int64_t numElements = 1;
863 for (int64_t dim : baseTy.getShape()) {
864 if (numElements > maxThreadPrivateStack / std::max<int64_t>(dim, 1))
865 return false;
866 numElements *= dim;
867 }
868 return elementSize * numElements < maxThreadPrivateStack;
869}
870
871/// True if the accumulate spans a block dim or is nested in a block-mapped
872/// loop, i.e. each block owns the elements it reduces across threads. A
873/// thread-only accumulate with no block context grid-strides its element loop
874/// onto blocks, so per-thread partials would be dropped; such reductions must
875/// stay shared.
876static bool reductionHasBlockContext(acc::ReductionAccumulateArrayOp accArr) {
877 auto hasBlock = [](mlir::acc::GPUParallelDimsAttr parDims) {
878 return parDims && llvm::any_of(parDims.getArray(),
879 [](auto pd) { return pd.isAnyBlock(); });
880 };
881 if (hasBlock(accArr.getParDimsAttr()))
882 return true;
883 for (scf::ParallelOp loop = accArr->getParentOfType<scf::ParallelOp>(); loop;
884 loop = loop->getParentOfType<scf::ParallelOp>()) {
885 if (hasBlock(mlir::acc::getParDimsAttr(loop)))
886 return true;
887 }
888 return false;
889}
890
891/// Returns the array reduction accumulate (through cast/view ops) that \p v
892/// feeds if it needs per-thread storage: its par_dims include a thread dim
893/// and it has block context so the cross-thread all_reduce is well defined.
894static acc::ReductionAccumulateArrayOp perThreadArrayReductionAccum(Value v) {
895 SmallVector<Value> worklist{v};
896 DenseSet<Value> seen;
897 while (!worklist.empty()) {
898 Value cur = worklist.pop_back_val();
899 if (!seen.insert(cur).second)
900 continue;
901 for (Operation *user : cur.getUsers()) {
902 if (acc::ReductionAccumulateArrayOp accArr =
903 dyn_cast<acc::ReductionAccumulateArrayOp>(user)) {
904 bool hasThread = false;
905 for (auto pd : accArr.getParDims().getArray())
906 hasThread |= pd.isAnyThread();
907 if (hasThread && reductionHasBlockContext(accArr))
908 return accArr;
909 continue;
910 }
911 SmallVector<Value> through;
912 if (getPassThroughResults(user, cur, through))
913 worklist.append(through.begin(), through.end());
914 else if (isa<ViewLikeOpInterface>(user))
915 worklist.append(user->result_begin(), user->result_end());
916 }
917 }
918 return nullptr;
919}
920
921/// Store the reduction identity to every element of a freshly allocated
922/// per-thread array accumulator so all lanes start from identity (the original
923/// init loop may only run on one lane).
924static void initPerThreadArrayAccum(OpBuilder &b, Location loc, Value alloca,
925 MemRefType baseTy,
926 arith::AtomicRMWKind kind) {
927 assert(baseTy.getRank() > 0 && baseTy.hasStaticShape() &&
928 "per-thread array reduction accumulator must be static ranked");
929 Value ident = createIdentityValue(b, loc, baseTy.getElementType(), kind,
930 /*useOnlyFiniteValue=*/true);
931 Value lb = arith::ConstantIndexOp::create(b, loc, 0);
932 Value step = arith::ConstantIndexOp::create(b, loc, 1);
933 SmallVector<Value> indices;
934 auto buildLoopNest = [&](auto &&self, unsigned dim) -> void {
935 if (dim == baseTy.getRank()) {
936 memref::StoreOp::create(b, loc, ident, alloca, indices);
937 return;
938 }
939
940 Value ub = arith::ConstantIndexOp::create(b, loc, baseTy.getShape()[dim]);
941 auto forOp = scf::ForOp::create(b, loc, lb, ub, step);
942 OpBuilder::InsertionGuard g(b);
943 b.setInsertionPoint(forOp.getBody()->getTerminator());
944 indices.push_back(forOp.getInductionVar());
945 self(self, dim + 1);
946 indices.pop_back();
947 };
948 buildLoopNest(buildLoopNest, 0);
949}
950
951/// True when \p writer stores a value other than the reduction identity of
952/// \p accArr. The per-thread partials of an array reduction are combined
953/// across the accumulate's thread dims, so such a store must run on a single
954/// lane of those dims: running it on every lane would add its contribution
955/// once per lane. Storing the identity is safe on every lane, and is how every
956/// lane's partial gets initialized.
957static bool
958isArrayReductionPartialUpdate(Operation *writer,
959 acc::ReductionAccumulateArrayOp accArr) {
960 memref::StoreOp store = dyn_cast<memref::StoreOp>(writer);
961 if (!store)
962 return false;
963 Value value = store.getValueToStore();
964 Type type = value.getType();
965 if (!type.isIntOrFloat())
966 return false;
967 std::optional<arith::AtomicRMWKind> kind =
968 translateACCReductionOperator(accArr.getReductionOperator(), type);
969 if (!kind)
970 return false;
971 bool isFloatKind = llvm::is_contained(
972 {arith::AtomicRMWKind::addf, arith::AtomicRMWKind::mulf,
973 arith::AtomicRMWKind::maximumf, arith::AtomicRMWKind::maxnumf,
974 arith::AtomicRMWKind::minimumf, arith::AtomicRMWKind::minnumf},
975 *kind);
976 if (isFloatKind != isa<FloatType>(type))
977 return false;
978 Attribute cst;
979 if (!matchPattern(value, m_Constant(&cst)))
980 return true;
981 OpBuilder b(writer->getContext());
982 for (bool useOnlyFiniteValue : {true, false}) {
983 TypedAttr ident = arith::getIdentityValueAttr(
984 *kind, type, b, writer->getLoc(), useOnlyFiniteValue);
985 if (cst == ident)
986 return false;
987 FloatAttr cstFloat = dyn_cast<FloatAttr>(cst);
988 FloatAttr identFloat = dyn_cast_if_present<FloatAttr>(ident);
989 if (cstFloat && identFloat &&
990 cstFloat.getValue().compare(identFloat.getValue()) ==
991 llvm::APFloat::cmpEqual)
992 return false;
993 }
994 return true;
995}
996
997std::optional<int64_t>
998ACCCGToGPULowering::isEligibleForSharedMemory(acc::PrivateLocalOp privateLocal,
999 MemRefType baseTy) {
1000 // Cross-thread array reduction accumulators must stay per-thread when their
1001 // storage scope includes thread_x. Gang-/worker-scoped array temps remain
1002 // eligible for shared memory.
1003 if (perThreadArrayReductionAccum(privateLocal.getResult()) &&
1004 storageHasThreadX(privateLocal, computeRegion))
1005 return std::nullopt;
1006 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
1007 FailureOr<bool> isCandidate = isPrivateLocalSharedMemoryCandidate(
1008 privateLocal, computeRegion, module, defaultPolicy, &accSupport);
1009 if (failed(isCandidate)) {
1010 hasFailed = true;
1011 return std::nullopt;
1012 }
1013 if (!isCandidate.value())
1014 return std::nullopt;
1015 std::optional<int64_t> upperBound =
1016 getPrivateLocalSharedMemoryUpperBoundBytes(privateLocal, computeRegion,
1017 module, defaultPolicy);
1018 assert(upperBound && "candidate private_local must have an upper bound");
1019 int64_t elementSize =
1020 getElementSizeInBytes(privateLocal.getLoc(), baseTy.getElementType());
1021 int64_t numElements = 1;
1022 for (int64_t dim : baseTy.getShape())
1023 numElements *= dim;
1024 return *upperBound / (elementSize * numElements);
1025}
1026
1027bool ACCCGToGPULowering::tryAllocateSharedMemory(int64_t bytes) {
1028 return sharedMemBudget.tryAllocate(bytes);
1029}
1030
1031void ACCCGToGPULowering::recordThreadPrivate(acc::PrivateLocalOp privateLocal) {
1032 std::string varName = accSupport.getVariableName(privateLocal.getResult());
1033 // A name that could not be recovered, or a compiler temp are skipped.
1034 if (varName.empty())
1035 return;
1036 // The same variable reaches this point once per acc.private_local it has.
1037 if (!llvm::is_contained(threadPrivateVarNames, varName))
1038 threadPrivateVarNames.push_back(varName);
1039}
1040
1041void ACCCGToGPULowering::recordGlobalMemory(acc::PrivatizeOp privatizeOp) {
1042 std::string varName = accSupport.getVariableName(privatizeOp.getResult());
1043 // A name that could not be recovered, or a compiler temp are skipped.
1044 if (varName.empty())
1045 return;
1046 // The same variable reaches this point once per acc.privatize it has.
1047 if (!llvm::is_contained(globalMemVarNames, varName))
1048 globalMemVarNames.push_back(varName);
1049}
1050
1051FailureOr<arith::AtomicRMWKind>
1052ACCCGToGPULowering::getReductionKind(acc::ReductionOperator redOp, Type type,
1053 Location loc) {
1054 if (std::optional<arith::AtomicRMWKind> kind =
1055 translateACCReductionOperator(redOp, type))
1056 return *kind;
1057
1058 std::string msg;
1059 llvm::raw_string_ostream os(msg);
1060 os << "reduction operator (" << redOp << ") for type " << type;
1061 (void)accSupport.emitNYI(loc, os.str());
1062 return failure();
1063}
1064
1065LogicalResult ACCCGToGPULowering::rewrite() {
1066
1067 // Pre-compute if thread-level reductions exist. ThreadY reduction generates
1068 // shuffles which require subgroup alignment (blockDim.x = subgroupSize),
1069 // meaning ThreadX lanes exist even without explicit ThreadX parallelism.
1070 // ThreadX is tracked too, to tell worker-only reductions from row shuffles.
1071 computeRegion->walk([&](acc::ReductionAccumulateOp op) {
1072 for (auto parDim : op.getParDimsAttr().getArray()) {
1073 hasThreadXReduction |= parDim.isThreadX();
1074 hasThreadYReduction |= parDim.isThreadY();
1075 }
1076 });
1077 computeRegion->walk([&](acc::ReductionAccumulateArrayOp op) {
1078 bool hasThread = false;
1079 for (auto parDim : op.getParDimsAttr().getArray()) {
1080 if (!parDim.isAnyBlock())
1081 hasThreadLevelArrayReduction = true;
1082 hasThread |= parDim.isAnyThread();
1083 }
1084 if (hasThread)
1085 if (acc::PrivateLocalOp privateLocal =
1086 getPrivateLocalForMemref(op.getMemref()))
1087 threadArrayAccumulators.try_emplace(privateLocal, op);
1088 });
1089
1090 // Pre-compute if any thread-level (vector or worker) routine call exists.
1091 // Such routines partition work across ThreadX/ThreadY and emit workgroup-wide
1092 // barriers internally (e.g. for shared memory alloca synchronization), so all
1093 // workgroup threads must reach the call site for those barriers to converge.
1094 computeRegion->walk([&](CallOpInterface callOp) -> WalkResult {
1095 if (mlir::acc::GPUParallelDimAttr parDim =
1096 getAccRoutineCallParDim(callOp, defaultPolicy)) {
1097 if (parDim.isThreadX() || parDim.isThreadY()) {
1098 hasThreadLevelRoutineCall = true;
1099 return WalkResult::interrupt();
1100 }
1101 }
1102 return WalkResult::advance();
1103 });
1104
1105 Location loc = computeRegion->getLoc();
1106 Value constantOne = arith::ConstantIndexOp::create(rewriter, loc, 1);
1107
1108 auto launchArgument = [&](gpu::Processor processor) -> Value {
1109 mlir::acc::GPUParallelDimAttr parDim = mlir::acc::GPUParallelDimAttr::get(
1110 computeRegion->getContext(), processor);
1111 std::optional<Value> maybeLaunchArg =
1112 computeRegion.getKnownLaunchArg(parDim);
1113 LLVM_DEBUG(llvm::dbgs() << "ACCCGToGPU: launch-arg: "
1114 << " parDim: " << parDim << " gpu: " << processor
1115 << " widthValue: "
1116 << maybeLaunchArg.value_or(constantOne) << "\n");
1117
1119 rewriter, loc, rewriter.getIndexType(),
1120 maybeLaunchArg.value_or(constantOne));
1121 };
1122 LLVM_DEBUG(llvm::dbgs() << "ACCCGToGPU: creating gpu launch op: \n");
1123
1124 // acc.compute_region keeps launch argument as block argument, for rewriting
1125 // we now replace these with gpu.launch dimensions.
1126 auto mapLaunchArguments = [&](gpu::Processor processor, Value launchArg) {
1127 mlir::acc::GPUParallelDimAttr parDim = mlir::acc::GPUParallelDimAttr::get(
1128 computeRegion->getContext(), processor);
1129 std::optional<Value> kernelArg = computeRegion.getLaunchArg(parDim);
1130 if (kernelArg)
1131 mapping.map(computeRegion.gpuParWidth(processor), launchArg);
1132 };
1133
1134 llvm::StringRef blockDimXName = "blockDim.x";
1135 llvm::StringRef blockDimYName = "blockDim.y";
1136 std::string deviceLabel = getDeviceRemarkQualifier(options.deviceType);
1137
1138 if (!computeRegion->getParentOfType<gpu::GPUFuncOp>()) {
1139 Value blockDimX = launchArgument(gpu::Processor::ThreadX);
1140 APInt bdxVal;
1141 if (matchPattern(blockDimX, m_ConstantInt(&bdxVal)))
1142 staticBlockDimX = bdxVal.getSExtValue();
1143 Value blockDimY = launchArgument(gpu::Processor::ThreadY);
1144 APInt bdyVal;
1145 if (matchPattern(blockDimY, m_ConstantInt(&bdyVal)))
1146 staticBlockDimY = bdyVal.getSExtValue();
1147 Value blockDimZ = launchArgument(gpu::Processor::ThreadZ);
1148 APInt bdzVal;
1149 if (matchPattern(blockDimZ, m_ConstantInt(&bdzVal)))
1150 staticBlockDimZ = bdzVal.getSExtValue();
1151 Value gridDimX = launchArgument(gpu::Processor::BlockX);
1152 Value gridDimY = launchArgument(gpu::Processor::BlockY);
1153 Value gridDimZ = launchArgument(gpu::Processor::BlockZ);
1154
1155 // The format of the message is:
1156 // Generating [serial] {deviceLabel} code with gridDim=32x1x1
1157 // blockDim=256x1x1
1158 accSupport.emitRemark(computeRegion, [&]() {
1159 auto getName = [&](Value val) -> std::string {
1160 // A negative width leaves the size to the launch.
1161 if (std::optional<int64_t> width = getConstantIntValue(val);
1162 width && *width < 0)
1163 return "(*)";
1164 std::string name = accSupport.getVariableName(val);
1165 return name.empty() ? "(*)" : name;
1166 };
1167 bool isEffectivelySerial =
1168 sameEffectiveValue(blockDimX, 1) &&
1169 sameEffectiveValue(blockDimY, 1) &&
1170 sameEffectiveValue(blockDimZ, 1) && sameEffectiveValue(gridDimX, 1) &&
1171 sameEffectiveValue(gridDimY, 1) && sameEffectiveValue(gridDimZ, 1);
1172 return (llvm::Twine("Generating ") +
1173 llvm::Twine(isEffectivelySerial ? "serial " : "") + deviceLabel +
1174 " code with gridDim=" + getName(gridDimX) + "x" +
1175 getName(gridDimY) + "x" + getName(gridDimZ) +
1176 " blockDim=" + getName(blockDimX) + "x" + getName(blockDimY) +
1177 "x" + getName(blockDimZ))
1178 .str();
1179 });
1180
1181 // Check if kernel has a stream operand for async execution
1182 if (mlir::Value streamValue = computeRegion.getStream()) {
1183 LLVM_DEBUG(llvm::dbgs()
1184 << "\nDEBUG: Creating async gpu.launch with stream: "
1185 << streamValue << "\n");
1186 launch = gpu::LaunchOp::create(
1187 rewriter, loc, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY,
1188 blockDimZ,
1189 /*dynamicSharedMemorySize=*/mlir::Value{},
1190 /*asyncTokenType=*/
1192 // Add the stream as an async dependency
1193 launch.getAsyncDependenciesMutable().append(streamValue);
1194 } else {
1195 LLVM_DEBUG(llvm::dbgs()
1196 << "\nDEBUG: No stream, creating sync gpu.launch\n");
1197 launch = gpu::LaunchOp::create(rewriter, loc, gridDimX, gridDimY,
1198 gridDimZ, blockDimX, blockDimY, blockDimZ);
1199 }
1200
1201 // Transfer kernel function name and module name from acc.compute_region to
1202 // gpu.launch if present
1203 if (auto kernelFuncName = computeRegion.getKernelFuncNameAttr())
1204 launch.setFunctionAttr(kernelFuncName);
1205 if (auto kernelModuleName = computeRegion.getKernelModuleNameAttr())
1206 launch.setModuleAttr(kernelModuleName);
1207
1208 rewriter.setInsertionPointToEnd(&launch.getBody().front());
1209 gpu::TerminatorOp::create(rewriter, loc);
1210 rewriter.setInsertionPointToStart(&launch.getBody().front());
1211 mapLaunchArguments(gpu::Processor::BlockX,
1212 gpu::GridDimOp::create(rewriter, loc,
1213 rewriter.getIndexType(),
1214 gpu::Dimension::x));
1215 mapLaunchArguments(gpu::Processor::BlockY,
1216 gpu::GridDimOp::create(rewriter, loc,
1217 rewriter.getIndexType(),
1218 gpu::Dimension::y));
1219 mapLaunchArguments(gpu::Processor::BlockZ,
1220 gpu::GridDimOp::create(rewriter, loc,
1221 rewriter.getIndexType(),
1222 gpu::Dimension::z));
1223 mapLaunchArguments(gpu::Processor::ThreadX,
1224 gpu::BlockDimOp::create(rewriter, loc,
1225 rewriter.getIndexType(),
1226 gpu::Dimension::x));
1227 mapLaunchArguments(gpu::Processor::ThreadY,
1228 gpu::BlockDimOp::create(rewriter, loc,
1229 rewriter.getIndexType(),
1230 gpu::Dimension::y));
1231 mapLaunchArguments(gpu::Processor::ThreadZ,
1232 gpu::BlockDimOp::create(rewriter, loc,
1233 rewriter.getIndexType(),
1234 gpu::Dimension::z));
1235 } else {
1236 // Do not create gpu.launch for acc routine and map
1237 // to block/thread index and block/grid size instead
1238 // of launch arguments, using created maps.
1239 OpBuilder::InsertionGuard guard(rewriter);
1240 rewriter.setInsertionPointToStart(computeRegion->getBlock());
1241 createForAllDimensions(rewriter, loc, threadIdMap, dimensionMap);
1242 mapLaunchArguments(gpu::Processor::BlockX,
1243 dimensionMap[gpu::Processor::BlockX]);
1244 mapLaunchArguments(gpu::Processor::BlockY,
1245 dimensionMap[gpu::Processor::BlockY]);
1246 mapLaunchArguments(gpu::Processor::BlockZ,
1247 dimensionMap[gpu::Processor::BlockZ]);
1248 mapLaunchArguments(gpu::Processor::ThreadX,
1249 dimensionMap[gpu::Processor::ThreadX]);
1250 mapLaunchArguments(gpu::Processor::ThreadY,
1251 dimensionMap[gpu::Processor::ThreadY]);
1252 mapLaunchArguments(gpu::Processor::ThreadZ,
1253 dimensionMap[gpu::Processor::ThreadZ]);
1254 }
1255
1256 // Map input arguments for compute region; we go from an IsolatedFromAbove
1257 // operation to gpu.launch which is not IsolatedFromAbove.
1258 preparePrivatizeExtentInsOperands();
1259 Block *body = computeRegion.getBody();
1260 unsigned numLaunchArgs = computeRegion.getLaunchArgs().size();
1261 ValueRange inputArgs = computeRegion.getInputArgs();
1262 for (unsigned i = numLaunchArgs; i < body->getNumArguments(); ++i)
1263 mapping.map(body->getArgument(i), inputArgs[i - numLaunchArgs]);
1264
1265 assert(computeRegion.getRegion().hasOneBlock() &&
1266 "compute region only supports one block region for now");
1267 // process all operations inside kernel region
1268 for (auto &op : computeRegion.getRegion().getBlocks().front().getOperations())
1269 processOp(&op);
1270
1271 for (auto &parLoop : loopReductions)
1272 postprocessLoopReduction(parLoop);
1273
1274 // Replace combine reloads of a reduction slot with the block-reduced value.
1275 // Only when it dominates the reload; otherwise keep the reload.
1276 if (!pendingCombineReloads.empty() && launch) {
1277 DominanceInfo domInfo(launch);
1278 for (auto &[slot, loadOp] : pendingCombineReloads) {
1279 llvm::DenseMap<Value, Value>::iterator it =
1280 reductionAccumValue.find(slot);
1281 if (it == reductionAccumValue.end())
1282 continue;
1283 if (!domInfo.dominates(it->second, loadOp.getOperation()))
1284 continue;
1285 rewriter.replaceOp(loadOp, ValueRange{it->second});
1286 }
1287 }
1288
1289 if (launch) {
1290 const int64_t subgroupSize = options.subgroupSize;
1291 const int64_t subgroupAlignMask = subgroupSize - 1;
1292
1293 // Adjust blockDim.x to be a multiple of subgroupSize. This is required
1294 // because:
1295 // - Subgroup reductions (gpu.all_reduce) require full subgroups
1296 // - Per-row workgroup barriers require blockDim.x aligned to subgroupSize
1297 // Tracked apart because only a ThreadX reduction shuffles within the row,
1298 // so only it needs the row to start at a subgroup boundary.
1299 bool needsThreadXAlign = false;
1300 bool needsThreadYAlign = false;
1301 bool alignThreadXReduction =
1302 getConstantIntValue(launch.getBlockSizeY()) != 1 ||
1303 getConstantIntValue(launch.getBlockSizeZ()) != 1;
1304
1305 // A reduction over both dimensions counts as a ThreadX one: it still
1306 // shuffles ThreadX lanes within the row.
1307 auto classifyAllReduce = [&](gpu::AllReduceOp allReduce) {
1308 bool hasThreadX = false;
1309 bool hasThreadY = false;
1310 for (auto parDim : mlir::acc::getParDimsAttr(allReduce).getArray()) {
1311 hasThreadX |= parDim.isThreadX();
1312 hasThreadY |= parDim.isThreadY();
1313 }
1314 if (hasThreadX && alignThreadXReduction)
1315 needsThreadXAlign = true;
1316 else if (hasThreadY)
1317 needsThreadYAlign = true;
1318 };
1319
1320 launch.walk(classifyAllReduce);
1321 // Also check if called routines have thread-level reductions.
1322 launch.walk([&](func::CallOp callOp) {
1323 if (gpu::GPUFuncOp callee =
1324 callOp->getParentOfType<ModuleOp>().lookupSymbol<gpu::GPUFuncOp>(
1325 callOp.getCallee()))
1326 callee.walk(classifyAllReduce);
1327 });
1328
1329 bool isShuffleEnabled = needsThreadXAlign || needsThreadYAlign;
1330
1331 std::optional<int64_t> constBlockDimX =
1332 getConstantIntValue(launch.getBlockSizeX());
1333 std::optional<int64_t> constBlockDimY =
1334 getConstantIntValue(launch.getBlockSizeY());
1335 std::optional<int64_t> constBlockDimZ =
1336 getConstantIntValue(launch.getBlockSizeZ());
1337
1338 // Skip subgroup alignment only when the total thread count is already
1339 // below a subgroup (constant blockDim.x in 2..subgroupSize-1 and
1340 // constant blockDim.y/z == 1). If blockDim.y/z > 1 or is unknown,
1341 // padding blockDim.x to a subgroup is still required so subgroups don't
1342 // cross row boundaries for row-local shuffle/ThreadY-barrier reductions.
1343 bool skipAlign = constBlockDimX && constBlockDimY && constBlockDimZ &&
1344 *constBlockDimX > 1 && *constBlockDimX < subgroupSize &&
1345 *constBlockDimY == 1 && *constBlockDimZ == 1;
1346
1347 // Padding a worker-only launch divides blockDim.y by the same factor and
1348 // leaves the folded-away workers as ThreadX lanes redoing each other's
1349 // work, so keep its shape instead.
1350 if (isSingleThreadWorkerLaunch())
1351 skipAlign = true;
1352 if (needsThreadYAlign && !needsThreadXAlign && !hasThreadYBarrier &&
1353 isWorkerOnlyShuffleLaunch())
1354 skipAlign = true;
1355
1356 if ((isShuffleEnabled || hasThreadYBarrier) && !skipAlign) {
1357 rewriter.setInsertionPoint(launch);
1358
1359 Value curBlockDimX = launch.getBlockSizeX();
1360 Value curBlockDimY = launch.getBlockSizeY();
1361 Value curBlockDimZ = launch.getBlockSizeZ();
1362
1363 // Emit a report on changing parallelism.
1364 accSupport.emitRemark(computeRegion, [&]() {
1365 auto getName = [&](Value val) -> std::string {
1366 std::string name = accSupport.getVariableName(val);
1367 return name.empty() ? "(*)" : name;
1368 };
1369 std::string blockDimXValStr = getName(curBlockDimX);
1370 std::string blockDimYValStr = getName(curBlockDimY);
1371 llvm::StringRef kind =
1372 isShuffleEnabled ? "Shuffle reduction" : "ThreadY barrier";
1373 return (llvm::Twine(kind) +
1374 " is generated while adjusting the number of threads into "
1375 "groups of " +
1376 llvm::Twine(subgroupSize) + ".\n\t" + blockDimXName + ": `" +
1377 blockDimXValStr + "` to `((" + blockDimXValStr + " + " +
1378 llvm::Twine(subgroupAlignMask) + ") / " +
1379 llvm::Twine(subgroupSize) + ") * " + llvm::Twine(subgroupSize) +
1380 "`\n" + "\t" + blockDimYName + ": `" + blockDimYValStr +
1381 "` to `max(1, (new-" + blockDimXName + " * " + blockDimYValStr +
1382 ") / new-" + blockDimXName + ")`")
1383 .str();
1384 });
1385
1386 // Update the ThreadX length and the numbers of ThreadY and ThreadZ.
1387 // When the original block dimensions are compile-time
1388 // constants, compute the adjusted dimensions as constants directly so
1389 // that the GpuKernelOutliningPass can set `known_block_size` on the
1390 // outlined gpu.func.
1391 Value newBlockDimX, newBlockDimY, newBlockDimZ;
1392 if (constBlockDimX && constBlockDimY && constBlockDimZ) {
1393 int64_t bdx = *constBlockDimX;
1394 int64_t bdy = *constBlockDimY;
1395 int64_t bdz = *constBlockDimZ;
1396 int64_t alignedBdx =
1397 ((bdx + subgroupAlignMask) / subgroupSize) * subgroupSize;
1398 int64_t numXYThreads = bdx * bdy;
1399 int64_t numThreads = numXYThreads * bdz;
1400 int64_t newBdy = std::max<int64_t>(1, numXYThreads / alignedBdx);
1401 int64_t newBdz =
1402 std::max<int64_t>(1, numThreads / (alignedBdx * newBdy));
1403 newBlockDimX =
1404 arith::ConstantIndexOp::create(rewriter, loc, alignedBdx);
1405 newBlockDimY = arith::ConstantIndexOp::create(rewriter, loc, newBdy);
1406 newBlockDimZ = arith::ConstantIndexOp::create(rewriter, loc, newBdz);
1407 } else {
1408 // numXYThreads = blockDim.x * blockDim.y
1409 Value numXYThreads =
1410 arith::MulIOp::create(rewriter, loc, curBlockDimX, curBlockDimY);
1411 Value numThreads =
1412 arith::MulIOp::create(rewriter, loc, numXYThreads, curBlockDimZ);
1413 // blockDim.x = ((blockDim.x + mask) / subgroupSize) * subgroupSize
1414 Value cstMask =
1415 arith::ConstantIndexOp::create(rewriter, loc, subgroupAlignMask);
1416 Value cstSubgroupSize =
1417 arith::ConstantIndexOp::create(rewriter, loc, subgroupSize);
1418 Value padded =
1419 arith::AddIOp::create(rewriter, loc, curBlockDimX, cstMask);
1420 Value subgroupsRequired =
1421 arith::DivUIOp::create(rewriter, loc, padded, cstSubgroupSize);
1422 newBlockDimX = arith::MulIOp::create(rewriter, loc, subgroupsRequired,
1423 cstSubgroupSize);
1424 // blockDim.y = max(1, numXYThreads / blockDim.x)
1425 Value quotient =
1426 arith::DivUIOp::create(rewriter, loc, numXYThreads, newBlockDimX);
1427 Value cst1 = arith::ConstantIndexOp::create(rewriter, loc, 1);
1428 newBlockDimY = arith::MaxUIOp::create(rewriter, loc, cst1, quotient);
1429 // blockDim.z = max(1, numThreads / (blockDim.x * blockDim.y))
1430 Value newNumXYThreads =
1431 arith::MulIOp::create(rewriter, loc, newBlockDimX, newBlockDimY);
1432 quotient =
1433 arith::DivUIOp::create(rewriter, loc, numThreads, newNumXYThreads);
1434 newBlockDimZ = arith::MaxUIOp::create(rewriter, loc, cst1, quotient);
1435 }
1436
1437 launch.getBlockSizeXMutable().assign(newBlockDimX);
1438 launch.getBlockSizeYMutable().assign(newBlockDimY);
1439 launch.getBlockSizeZMutable().assign(newBlockDimZ);
1440 }
1441 }
1442
1443 if (hasFailed)
1444 return failure();
1445
1446 if (!threadPrivateVarNames.empty()) {
1447 accSupport.emitRemark(computeRegion, [&]() {
1448 return (llvm::Twine("Local memory or registers used for ") +
1449 llvm::join(threadPrivateVarNames, ","))
1450 .str();
1451 });
1452 }
1453
1454 if (!sharedMemPrivateVarNames.empty()) {
1455 accSupport.emitRemark(computeRegion, [&]() {
1456 return (llvm::Twine("GPU shared memory used for ") +
1457 llvm::join(sharedMemPrivateVarNames, ","))
1458 .str();
1459 });
1460 }
1461
1462 if (!globalMemVarNames.empty()) {
1463 accSupport.emitRemark(computeRegion, [&]() {
1464 return (llvm::Twine("GPU global memory used for ") +
1465 llvm::join(globalMemVarNames, ","))
1466 .str();
1467 });
1468 }
1469
1470 rewriter.eraseOp(computeRegion);
1471 return success();
1472}
1473
1474/// True when this accumulate is redundant in a nested reduction chain: the
1475/// value is a load of the destination memref and a sibling
1476/// acc.reduction_combine with block par_dims has already reduced %M across
1477/// threads in the block.
1478///
1479/// %v = memref.load %M[]
1480/// acc.reduction_accumulate %v to %M ...
1481/// acc.reduction_combine %M into %parent ... {block par_dims}
1482///
1483/// Lowering the accumulate again would double-count. Detection is structural;
1484/// nested reductions into per-thread privates do not match because their
1485/// combines are not block-scoped.
1486static bool isRedundantChainAccumulate(acc::ReductionAccumulateOp op) {
1487 Value memref = op.getMemref();
1488 memref::LoadOp loadOp = op.getValue().getDefiningOp<memref::LoadOp>();
1489 if (!loadOp || loadOp.getMemRef() != memref)
1490 return false;
1491 for (Operation *user : memref.getUsers()) {
1492 acc::ReductionCombineOp combineOp = dyn_cast<acc::ReductionCombineOp>(user);
1493 if (!combineOp || combineOp.getDestMemref() != memref)
1494 continue;
1495 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
1496 getReductionCombineParDims(combineOp);
1497 if (llvm::any_of(parDims, [](mlir::acc::GPUParallelDimAttr d) {
1498 return d.isAnyBlock();
1499 })) {
1500 return true;
1501 }
1502 }
1503 return false;
1504}
1505
1506static GPUParallelDimsAttr
1507getPrivateParDims(acc::PrivateLocalOp privateLocal,
1508 acc::ComputeRegionOp computeRegion) {
1509 if (GPUParallelDimsAttr parDims = acc::getParDimsAttr(privateLocal))
1510 return parDims;
1511 if (acc::PrivatizeOp privatize = getPrivatizeOp(privateLocal, computeRegion))
1512 return privatize.getParDimsAttr();
1513 return {};
1514}
1515
1516/// True when \p privateLocal has one private slot per ThreadY row.
1517static bool isThreadYPrivate(acc::PrivateLocalOp privateLocal, bool allowBlock,
1518 acc::ComputeRegionOp computeRegion) {
1519 if (!privateLocal)
1520 return false;
1521 GPUParallelDimsAttr parDims = getPrivateParDims(privateLocal, computeRegion);
1522 if (!parDims)
1523 return false;
1524 return llvm::any_of(parDims.getArray(),
1525 [](auto dim) { return dim.isThreadY(); }) &&
1526 llvm::all_of(parDims.getArray(), [=](auto dim) {
1527 return dim.isThreadY() || (allowBlock && dim.isAnyBlock());
1528 });
1529}
1530
1531struct ThreadYBroadeningInfo {
1532 bool hasActiveWorkerCombine = false;
1533 bool hasExplicitInactiveCombine = false;
1534 bool hasBroadeningConflict = false;
1535 Operation *diagnosticOp = nullptr;
1536
1537 void merge(const ThreadYBroadeningInfo &other) {
1538 hasActiveWorkerCombine |= other.hasActiveWorkerCombine;
1539 hasExplicitInactiveCombine |= other.hasExplicitInactiveCombine;
1540 hasBroadeningConflict |= other.hasBroadeningConflict;
1541 if (!diagnosticOp)
1542 diagnosticOp = other.diagnosticOp;
1543 }
1544};
1545
1546/// True when executing \p op on additional ThreadY rows may change behavior.
1547static bool hasUnsafeEffectsWhenBroadening(Operation *op) {
1548 if (auto effectOp = dyn_cast<MemoryEffectOpInterface>(op)) {
1549 SmallVector<MemoryEffects::EffectInstance> effects;
1550 effectOp.getEffects(effects);
1551 return llvm::any_of(effects, [](const auto &effect) {
1552 return !isa<MemoryEffects::Read>(effect.getEffect());
1553 });
1554 }
1555 return !op->hasTrait<OpTrait::HasRecursiveMemoryEffects>();
1556}
1557
1558/// True when \p accumulator is the destination of a separate block-scoped
1559/// combine, so it holds a distinct per-worker partial rather than a broadcast.
1560static bool isFedByInnerBlockCombine(acc::PrivateLocalOp accumulator,
1561 Operation *selfCombine) {
1562 if (!accumulator)
1563 return false;
1564 for (Operation *user : accumulator.getResult().getUsers()) {
1565 if (user == selfCombine)
1566 continue;
1567 auto combineOp = dyn_cast<acc::ReductionCombineOp>(user);
1568 if (!combineOp ||
1569 unwrapMemRefConversion(combineOp.getDestMemref()).getDefiningOp() !=
1570 accumulator.getOperation())
1571 continue;
1572 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
1573 getReductionCombineParDims(combineOp);
1574 if (llvm::any_of(parDims, [](mlir::acc::GPUParallelDimAttr d) {
1575 return d.isAnyBlock();
1576 }))
1577 return true;
1578 }
1579 return false;
1580}
1581
1582/// Records whether \p combineOp requires ThreadY to remain active.
1583static void classifyThreadYCombine(ThreadYBroadeningInfo &info,
1584 Operation *combineOp, Value src, Value dest,
1585 ArrayRef<GPUParallelDimAttr> parDims,
1586 acc::ComputeRegionOp computeRegion) {
1587 bool hasThreadY = llvm::any_of(
1588 parDims, [](GPUParallelDimAttr parDim) { return parDim.isThreadY(); });
1589 bool hasBlock = llvm::any_of(
1590 parDims, [](GPUParallelDimAttr parDim) { return parDim.isAnyBlock(); });
1591 acc::PrivateLocalOp srcPrivate =
1592 unwrapMemRefConversion(src).getDefiningOp<acc::PrivateLocalOp>();
1593 acc::PrivateLocalOp destPrivate =
1594 unwrapMemRefConversion(dest).getDefiningOp<acc::PrivateLocalOp>();
1595 bool hasPrivateDest = isa<acc::ReductionCombineOp>(combineOp) && srcPrivate &&
1596 destPrivate &&
1597 getPrivatizeOp(srcPrivate, computeRegion) !=
1598 getPrivatizeOp(destPrivate, computeRegion);
1599 if (hasThreadY && hasBlock &&
1600 isThreadYPrivate(srcPrivate, hasPrivateDest, computeRegion)) {
1601 info.hasActiveWorkerCombine = true;
1602 return;
1603 }
1604
1605 // A block_y+thread_y accumulator fed by an inner block-scoped combine holds
1606 // a distinct partial per worker row, so its combine runs on every row; a
1607 // plain worker accumulate broadcasts via all_reduce and stays row-zero.
1608 if (hasThreadY && hasBlock &&
1609 isThreadYPrivate(srcPrivate, /*allowBlock=*/true, computeRegion) &&
1610 isFedByInnerBlockCombine(srcPrivate, combineOp)) {
1611 info.hasActiveWorkerCombine = true;
1612 return;
1613 }
1614
1615 info.hasExplicitInactiveCombine = true;
1616 if (!info.diagnosticOp)
1617 info.diagnosticOp = combineOp;
1618}
1619
1620/// ThreadY must remain active for hierarchical combines over worker rows.
1621/// Broadening is rejected when siblings require inactive ThreadY or have side
1622/// effects; nested predicates enforce their own safety.
1623static ThreadYBroadeningInfo
1624analyzeThreadYBroadening(Block &predicateBlock,
1625 acc::ComputeRegionOp computeRegion) {
1626 ThreadYBroadeningInfo info;
1627 for (Operation &nestedOp : predicateBlock) {
1628 if (acc::PredicateRegionOp nestedPredicate =
1629 dyn_cast<acc::PredicateRegionOp>(nestedOp)) {
1630 ThreadYBroadeningInfo nestedInfo = analyzeThreadYBroadening(
1631 nestedPredicate.getRegion().front(), computeRegion);
1632 info.hasActiveWorkerCombine |= nestedInfo.hasActiveWorkerCombine;
1633 continue;
1634 }
1635 if (acc::ReductionCombineOp combineOp =
1636 dyn_cast<acc::ReductionCombineOp>(nestedOp)) {
1637 classifyThreadYCombine(
1638 info, combineOp, combineOp.getSrcMemref(), combineOp.getDestMemref(),
1639 getReductionCombineParDims(combineOp), computeRegion);
1640 continue;
1641 }
1642 if (acc::ReductionCombineRegionOp combineRegionOp =
1643 dyn_cast<acc::ReductionCombineRegionOp>(nestedOp)) {
1644 classifyThreadYCombine(info, combineRegionOp, combineRegionOp.getSrcVar(),
1645 combineRegionOp.getDestVar(),
1646 getReductionCombineParDims(combineRegionOp),
1647 computeRegion);
1648 continue;
1649 }
1650 if (nestedOp.getNumRegions() != 0) {
1651 if (hasUnsafeEffectsWhenBroadening(&nestedOp)) {
1652 info.hasBroadeningConflict = true;
1653 if (!info.diagnosticOp)
1654 info.diagnosticOp = &nestedOp;
1655 }
1656 for (Region &region : nestedOp.getRegions())
1657 for (Block &nestedBlock : region)
1658 info.merge(analyzeThreadYBroadening(nestedBlock, computeRegion));
1659 continue;
1660 }
1661 if (hasUnsafeEffectsWhenBroadening(&nestedOp)) {
1662 info.hasBroadeningConflict = true;
1663 if (!info.diagnosticOp)
1664 info.diagnosticOp = &nestedOp;
1665 }
1666 }
1667 return info;
1668}
1669
1670std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
1671 SmallVector<mlir::acc::GPUParallelDimAttr>>
1672ACCCGToGPULowering::computeActiveAndInactiveParDims(Operation *op,
1673 Block *block) {
1674 MLIRContext *ctx = computeRegion->getContext();
1675
1676 mlir::acc::GPUParallelDimAttr routineParDim;
1677 if (isInsideACCSpecializedRoutine(computeRegion)) {
1678 FunctionOpInterface funcOp =
1679 computeRegion->getParentOfType<FunctionOpInterface>();
1680 routineParDim = getSpecializedRoutineDim(funcOp, defaultPolicy);
1681 }
1682
1683 // The active set is precomputed separately from the ownership par_dims for
1684 // privatizations, and a predicate region may likewise state which dims run
1685 // it unpredicated; prefer that attribute when present. The inactive dims are
1686 // the launch dims which are not active.
1687 if (isa<acc::PrivateLocalOp, acc::PrivatizeOp, acc::PredicateRegionOp>(op)) {
1688 if (mlir::acc::ActiveParDimsAttr precomputedActiveParDims =
1690 mlir::acc::GPUParallelDimAttr lowestParDim =
1691 mlir::acc::GPUParallelDimAttr::threadXDim(ctx);
1692
1693 SmallVector<mlir::acc::GPUParallelDimAttr> launchParDims;
1694 if (routineParDim) {
1695 for (mlir::acc::GPUParallelDimAttr parDim = routineParDim;
1696 parDim.getOrder() >= lowestParDim.getOrder();
1697 parDim = parDim.getOneLower()) {
1698 mlir::acc::insertParDim(launchParDims, parDim);
1699 }
1700 } else {
1701 launchParDims = computeRegion.getLaunchParDims();
1702 }
1703
1704 SmallVector<mlir::acc::GPUParallelDimAttr> activeParDims(
1705 precomputedActiveParDims.getArray());
1706 SmallVector<mlir::acc::GPUParallelDimAttr> inactiveParDims;
1707 for (mlir::acc::GPUParallelDimAttr launchParDim : launchParDims) {
1708 if (launchParDim.getOrder() < lowestParDim.getOrder())
1709 break;
1710 if (!llvm::is_contained(activeParDims, launchParDim))
1711 inactiveParDims.push_back(launchParDim);
1712 }
1713 return std::pair{activeParDims, inactiveParDims};
1714 }
1715 }
1716
1717 SmallVector<mlir::acc::GPUParallelDimAttr> ancestorParDims =
1718 getAncestorParDims(op);
1719 // Preserve whether there were any structural ancestor par-dims before
1720 // we start augmenting them based on inner uses (e.g. private_local).
1721 // This is needed for gang redundancy check - stores to worker-indexed
1722 // private_local should not disable redundant gang execution.
1723 bool noStructuralAncestorParDims =
1724 llvm::none_of(ancestorParDims, [](auto pd) { return !pd.isSeq(); });
1725
1726 if (routineParDim) {
1727 if (routineParDim.isThreadX()) {
1728 mlir::acc::insertParDim(ancestorParDims,
1729 mlir::acc::GPUParallelDimAttr::threadYDim(ctx));
1730 }
1731 mlir::acc::insertParDim(ancestorParDims,
1732 mlir::acc::GPUParallelDimAttr::blockXDim(ctx));
1733 }
1734
1735 // acc.private_local should use the same par_dims as acc.reduction_accumulate.
1736 if (acc::PrivateLocalOp privateLocalOp = dyn_cast<acc::PrivateLocalOp>(op)) {
1737 for (Operation *user : privateLocalOp.getResult().getUsers()) {
1738 if (acc::ReductionAccumulateOp accumulateOp =
1739 dyn_cast<acc::ReductionAccumulateOp>(user)) {
1740 if (accumulateOp.getMemref() == privateLocalOp.getResult()) {
1741 for (mlir::acc::GPUParallelDimAttr parDim :
1742 accumulateOp.getParDims().getArray()) {
1743 mlir::acc::insertParDim(ancestorParDims, parDim);
1744 }
1745 }
1746 }
1747 // For decomposed complex reductions, the private_local is consumed
1748 // by an acc.reduction_combine{,_region} (no acc.reduction_accumulate
1749 // user). Mirror the par_dims so this private_local is treated as the
1750 // accumulator at the same parallelism level as a scalar reduction
1751 // would be (per-thread, not block-shared).
1752 if (acc::ReductionCombineOp combineOp =
1753 dyn_cast<acc::ReductionCombineOp>(user)) {
1754 if (combineOp.getSrcMemref() == privateLocalOp.getResult()) {
1755 for (mlir::acc::GPUParallelDimAttr parDim :
1756 getReductionCombineParDims(combineOp)) {
1757 mlir::acc::insertParDim(ancestorParDims, parDim);
1758 }
1759 }
1760 }
1761 if (auto combineRegionOp =
1762 dyn_cast<acc::ReductionCombineRegionOp>(user)) {
1763 if (combineRegionOp.getSrcVar() == privateLocalOp.getResult()) {
1764 for (mlir::acc::GPUParallelDimAttr parDim :
1765 getReductionCombineParDims(combineRegionOp)) {
1766 mlir::acc::insertParDim(ancestorParDims, parDim);
1767 }
1768 }
1769 }
1770 }
1771 // A dynamically-shaped privatization is materialized as a strided view
1772 // whose type does not reveal its parallel scope. Keep its own par_dims
1773 // active so the view is materialized (and predicated) per owning
1774 // thread/block. Statically-shaped privatizations are left to the stack-fit
1775 // decision so only do this for dynamic shapes.
1776 acc::PrivateType privTy =
1777 cast<acc::PrivateType>(privateLocalOp.getPrivatized().getType());
1778 MemRefType baseTy = getPrivateBaseMemRefType(
1779 privTy.getBaseTy(), computeRegion->getParentOfType<ModuleOp>());
1780 if (!baseTy.hasStaticShape()) {
1781 GPUParallelDimsAttr ownParDims =
1782 getPrivateParDims(privateLocalOp, computeRegion);
1783 if (ownParDims)
1784 for (GPUParallelDimAttr parDim : ownParDims.getArray())
1785 mlir::acc::insertParDim(ancestorParDims, parDim);
1786 }
1787 }
1788
1789 bool hasBlock = false;
1790 for (mlir::acc::GPUParallelDimAttr parDim : ancestorParDims)
1791 if (parDim.isAnyBlock())
1792 hasBlock = true;
1793
1794 mlir::acc::GPUParallelDimAttr lowestParDim =
1795 mlir::acc::GPUParallelDimAttr::threadXDim(ctx);
1796 if (block) {
1797 ThreadYBroadeningInfo threadYInfo =
1798 analyzeThreadYBroadening(*block, computeRegion);
1799
1800 auto applyCombineParDims =
1801 [&](ArrayRef<mlir::acc::GPUParallelDimAttr> combineParDims) {
1802 for (mlir::acc::GPUParallelDimAttr parDim : combineParDims)
1803 mlir::acc::removeParDim(ancestorParDims, parDim);
1804 return success();
1805 };
1806 block->walk([&](Operation *op) -> WalkResult {
1807 // Writes to acc.private_local must keep the privatization's par_dims
1808 // active so the write runs on all owning threads instead of being
1809 // predicated to a single lane. The exception is an update of an array
1810 // reduction partial, which stays on one lane of the thread dims the
1811 // partials are combined across.
1812 auto addPrivateStoreParDims = [&](Value target) {
1813 if (auto privateLocalOp = getPrivateLocalForMemref(target)) {
1814 GPUParallelDimsAttr parDimsAttr =
1815 getPrivateParDims(privateLocalOp, computeRegion);
1816 if (!parDimsAttr)
1817 return;
1818 acc::ReductionAccumulateArrayOp accArr =
1819 threadArrayAccumulators.lookup(privateLocalOp);
1820 bool isPartialUpdate =
1821 accArr && isArrayReductionPartialUpdate(op, accArr);
1822 for (auto parDim : parDimsAttr.getArray()) {
1823 if (isPartialUpdate && parDim.isAnyThread() &&
1824 llvm::is_contained(accArr.getParDims().getArray(), parDim))
1825 continue;
1826 mlir::acc::insertParDim(ancestorParDims, parDim);
1827 }
1828 }
1829 };
1830 if (auto memEffects = dyn_cast<MemoryEffectOpInterface>(op)) {
1831 SmallVector<MemoryEffects::EffectInstance> effects;
1832 memEffects.getEffects(effects);
1833 for (const MemoryEffects::EffectInstance &effect : effects) {
1834 if (isa<MemoryEffects::Write>(effect.getEffect()) &&
1835 effect.getValue())
1836 addPrivateStoreParDims(effect.getValue());
1837 }
1838 }
1839 // Consider ACC routine calls; routine calls should be predicated up to
1840 // one level above the parallel dimension of the callee.
1841 if (CallOpInterface callOp = dyn_cast<CallOpInterface>(op)) {
1842 if (mlir::acc::GPUParallelDimAttr parDim =
1843 getAccRoutineCallParDim(callOp, defaultPolicy)) {
1844 if (parDim.isBlockZ())
1845 lowestParDim = parDim;
1846 else
1847 lowestParDim = parDim.getOneHigher();
1848 }
1849 }
1850 // acc.reduction_combine_region should be predicated with the par_dims of
1851 // acc.reduction_accumulate. This is required when using combine between
1852 // kernel and loop in combined constructs.
1853 if (acc::ReductionCombineOp reductionCombineOp =
1854 dyn_cast<acc::ReductionCombineOp>(op)) {
1855 if (failed(applyCombineParDims(
1856 getReductionCombineParDims(reductionCombineOp))))
1857 return WalkResult::interrupt();
1858 }
1859 if (acc::ReductionCombineRegionOp combineRegionOp =
1860 dyn_cast<acc::ReductionCombineRegionOp>(op)) {
1861 if (failed(applyCombineParDims(
1862 getReductionCombineParDims(combineRegionOp))))
1863 return WalkResult::interrupt();
1864 }
1865 // An array accumulate reduces across its par_dims via gpu.all_reduce, so
1866 // all those threads must execute it - treat them as active (unlike the
1867 // scalar accumulate, which is active through its enclosing scf.parallel).
1868 if (acc::ReductionAccumulateArrayOp accArrayOp =
1869 dyn_cast<acc::ReductionAccumulateArrayOp>(op)) {
1870 for (mlir::acc::GPUParallelDimAttr parDim :
1871 accArrayOp.getParDims().getArray()) {
1872 mlir::acc::insertParDim(ancestorParDims, parDim);
1873 }
1874 }
1875 return WalkResult::advance();
1876 });
1877 mlir::acc::GPUParallelDimAttr threadY =
1878 mlir::acc::GPUParallelDimAttr::threadYDim(ctx);
1879 bool baselineThreadYActive = llvm::is_contained(ancestorParDims, threadY);
1880 if (threadYInfo.hasActiveWorkerCombine && !baselineThreadYActive) {
1881 if (threadYInfo.hasExplicitInactiveCombine ||
1882 threadYInfo.hasBroadeningConflict) {
1883 Operation *diagnosticOp =
1884 threadYInfo.diagnosticOp ? threadYInfo.diagnosticOp : op;
1885 (void)accSupport.emitNYI(
1886 diagnosticOp->getLoc(),
1887 "operations in the same predicate region require incompatible "
1888 "ThreadY predication");
1889 hasFailed = true;
1890 return {};
1891 }
1892 mlir::acc::insertParDim(ancestorParDims, threadY);
1893 }
1894 }
1895
1896 // Obtain launch dimensions
1897 SmallVector<mlir::acc::GPUParallelDimAttr> launchParDims;
1898 if (routineParDim) {
1899 for (mlir::acc::GPUParallelDimAttr parDim = routineParDim;
1900 parDim.getOrder() >= lowestParDim.getOrder();
1901 parDim = parDim.getOneLower()) {
1902 mlir::acc::insertParDim(launchParDims, parDim);
1903 }
1904 } else {
1905 launchParDims = computeRegion.getLaunchParDims();
1906 }
1907
1908 // Compute dimensions that execute op
1909 SmallVector<mlir::acc::GPUParallelDimAttr> activeParDims, inactiveParDims;
1910 for (mlir::acc::GPUParallelDimAttr launchParDim : launchParDims) {
1911 if (launchParDim.getOrder() < lowestParDim.getOrder())
1912 break;
1913 if (llvm::find(ancestorParDims, launchParDim) != ancestorParDims.end() ||
1914 (launchParDim.isAnyBlock() &&
1915 (noStructuralAncestorParDims || hasBlock))) {
1916 activeParDims.push_back(launchParDim);
1917 } else {
1918 inactiveParDims.push_back(launchParDim);
1919 }
1920 }
1921
1922 return std::pair{activeParDims, inactiveParDims};
1923}
1924
1925Value ACCCGToGPULowering::emitPredicate(
1926 Location loc, SmallVector<mlir::acc::GPUParallelDimAttr> &inactiveParDims) {
1927 Value predicate;
1928 for (mlir::acc::GPUParallelDimAttr inactiveParDim : inactiveParDims) {
1929 Value threadId = getGPUThreadIdFor(inactiveParDim.getProcessor());
1930 TypedAttr zeroAttr = rewriter.getZeroAttr(threadId.getType());
1931 Value zero = arith::ConstantOp::create(rewriter, loc, zeroAttr);
1932 Value cmp = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
1933 threadId, zero);
1934 if (predicate)
1935 predicate = arith::AndIOp::create(rewriter, loc, cmp, predicate);
1936 else
1937 predicate = cmp;
1938 }
1939 return predicate;
1940}
1941
1942void ACCCGToGPULowering::createBarrier(
1943 Location loc, mlir::acc::GPUParallelDimsAttr parDimsAttr) {
1944 bool hasAnyBlock = false, hasThreadY = false, hasThreadX = false;
1945 for (auto parDim : parDimsAttr.getArray()) {
1946 if (parDim.isAnyBlock())
1947 hasAnyBlock = true;
1948 if (parDim.isThreadY())
1949 hasThreadY = true;
1950 if (parDim.isThreadX())
1951 hasThreadX = true;
1952 }
1953
1954 if (hasAnyBlock || hasThreadY)
1955 emitGPUBarrierWorkgroup(rewriter, loc);
1956 else if (hasThreadX)
1957 createPerRowBarrier(loc);
1958}
1959
1960void ACCCGToGPULowering::createPerRowBarrier(Location loc) {
1961 // A row of a (1, N, 1) launch is a single thread; a subgroup barrier would
1962 // instead synchronize N workers.
1963 if (isSingleThreadWorkerLaunch())
1964 return;
1965
1966 // A worker-only row narrower than a subgroup covers only part of one, so
1967 // synchronize just its lanes. Both paths leave hasThreadYBarrier unset, so
1968 // the launch is not padded on account of this barrier.
1969 if (isWorkerOnlyShuffleLaunch() && staticBlockDimX < options.subgroupSize) {
1970 emitGPUBarrierRow(rewriter, loc, staticBlockDimX, options.subgroupSize);
1971 return;
1972 }
1973
1974 hasThreadYBarrier = true;
1975
1976 if (staticBlockDimX <= options.subgroupSize) {
1977 emitGPUBarrierSubgroup(rewriter, loc);
1978 return;
1979 }
1980
1981 if (options.deviceType != mlir::acc::DeviceType::Nvidia) {
1982 (void)accSupport.emitNYI(
1983 loc,
1984 "per-row barrier to support worker parallelism on non-NVIDIA device");
1985 return;
1986 }
1987
1988 // Per-row barrier with fully runtime branching.
1989 // Three mutually exclusive paths:
1990 // blockDim.y == 1 -> gpu.barrier (workgroup-wide, only one worker)
1991 // blockDim.x <= subgroupSize -> gpu.barrier scope<subgroup>
1992 // blockDim.x > subgroupSize -> nvvm.barrier (tid.y + 1), blockDim.x
1993 // (named)
1994 //
1995 // Per-row barriers use tid.y+1 so IDs start at 1, avoiding clash with
1996 // barrier 0. When blockDim.y >= 16, worker 15's ID (16) wraps to
1997 // physical barrier 0; this is safe because named barriers are reusable
1998 // resources - workgroup-wide and per-row barriers on the same physical
1999 // barrier execute at different program points and never overlap.
2000 Value blockDimX = gpu::BlockDimOp::create(
2001 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
2002 Value blockDimY = gpu::BlockDimOp::create(
2003 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::y);
2004 Value cst1 = arith::ConstantIndexOp::create(rewriter, loc, 1);
2005 Value isSingleWorker = arith::CmpIOp::create(
2006 rewriter, loc, arith::CmpIPredicate::eq, blockDimY, cst1);
2007
2008 auto outerIf = scf::IfOp::create(rewriter, loc, isSingleWorker,
2009 /*withElseRegion=*/true);
2010
2011 // Then: blockDim.y == 1 -> workgroup-wide barrier (safe, only one worker)
2012 rewriter.setInsertionPointToStart(&outerIf.getThenRegion().front());
2013 emitGPUBarrierWorkgroup(rewriter, loc);
2014
2015 // Else: blockDim.y > 1 - choose between subgroup sync and named barrier
2016 rewriter.setInsertionPointToStart(&outerIf.getElseRegion().front());
2017 Value cstSubgroupSize =
2018 arith::ConstantIndexOp::create(rewriter, loc, options.subgroupSize);
2019 Value isSubgroupSized = arith::CmpIOp::create(
2020 rewriter, loc, arith::CmpIPredicate::ule, blockDimX, cstSubgroupSize);
2021
2022 auto innerIf = scf::IfOp::create(rewriter, loc, isSubgroupSized,
2023 /*withElseRegion=*/true);
2024
2025 // Then: blockDim.x <= subgroupSize -> subgroup barrier (one worker per
2026 // subgroup)
2027 rewriter.setInsertionPointToStart(&innerIf.getThenRegion().front());
2028 emitGPUBarrierSubgroup(rewriter, loc);
2029
2030 // Else: blockDim.x > subgroupSize -> per-row named barrier with tid.y + 1.
2031 // The 1024-thread-per-block hardware limit with subgroup-aligned blockDim.x
2032 // (>= 64 here) guarantees blockDim.y <= 16, so IDs span at most 16
2033 // physical barriers (0-15) with no aliasing across workers.
2034 rewriter.setInsertionPointToStart(&innerIf.getElseRegion().front());
2035 Value threadYId = gpu::ThreadIdOp::create(
2036 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::y);
2037 Value barrierId = arith::AddIOp::create(rewriter, loc, threadYId, cst1);
2038 Type i32Ty = rewriter.getI32Type();
2039 Value barrierId32 =
2040 arith::IndexCastOp::create(rewriter, loc, i32Ty, barrierId);
2041 Value numberOfThreads32 =
2042 arith::IndexCastOp::create(rewriter, loc, i32Ty, blockDimX);
2043
2044 // GPU dialect named barriers do not have a means to create a custom barrier
2045 // id. Thus use nvvm directly.
2046 assert(options.deviceType == mlir::acc::DeviceType::Nvidia);
2047 NVVM::BarrierOp::create(rewriter, loc, barrierId32, numberOfThreads32);
2048
2049 rewriter.setInsertionPointAfter(outerIf);
2050}
2051
2052/// Whether any later sibling of \p loopOp (or a loop nested inside one) is a
2053/// loop, i.e. whether some subsequent loop in the same region may read what
2054/// \p loopOp wrote. Used to skip a barrier after the last loop, where nothing
2055/// reads the data afterward.
2056static bool hasSubsequentLoopSibling(Operation *loopOp) {
2057 for (Operation *next = loopOp->getNextNode(); next;
2058 next = next->getNextNode()) {
2059 if (isa<scf::ParallelOp, scf::ForOp>(next))
2060 return true;
2061 bool nested = false;
2062 next->walk([&](Operation *op) {
2063 if (isa<scf::ParallelOp, scf::ForOp>(op)) {
2064 nested = true;
2065 return WalkResult::interrupt();
2066 }
2067 return WalkResult::advance();
2068 });
2069 if (nested)
2070 return true;
2071 }
2072 return false;
2073}
2074
2075/// Nearest enclosing sequential loop ancestor of \p op.
2076static LoopLikeOpInterface findFirstSequentialLoop(Operation *op) {
2077 auto isAllSequentialParDims = [](scf::ParallelOp par) -> bool {
2078 mlir::acc::GPUParallelDimsAttr pd = mlir::acc::getParDimsAttr(par);
2079 if (!pd || pd.getArray().empty())
2080 return false;
2081 return llvm::all_of(pd.getArray(), [](mlir::acc::GPUParallelDimAttr d) {
2082 return d.isSeq();
2083 });
2084 };
2085
2086 for (Operation *p = op->getParentOp(); p; p = p->getParentOp()) {
2087 // Do not need to check scf.for op's parents
2088 if (isa<scf::ForOp>(p))
2089 return cast<LoopLikeOpInterface>(p);
2090 if (scf::ParallelOp parOp = dyn_cast<scf::ParallelOp>(p)) {
2091 if (isAllSequentialParDims(parOp))
2092 return cast<LoopLikeOpInterface>(p);
2093 }
2094 }
2095 return nullptr;
2096}
2097
2098// A sequential loop that uses gang-private shared memory needs a
2099// workgroup-wide barrier afterward so every thread in the block observes the
2100// same state. When more work still lies between the loop and the next
2101// thread-reconvergence point in the same block, that barrier must follow that
2102// work; not sit immediately after the loop.
2103//
2104// The helpers below mark loop-body closure and other reconvergence points
2105// where any postponed barrier must be inserted.
2106
2107/// Marks the end of a loop body's iteration in the current block.
2108static bool isLoopBodyClosureOp(Operation *op) {
2109 return isa<scf::ReduceOp, scf::YieldOp, acc::YieldOp>(op);
2110}
2111
2112/// Thread-reconvergence point where any postponed post-loop barrier for earlier
2113/// loops in this block must be inserted before proceeding.
2114static bool isDeferredBarrierFlushPoint(Operation *op) {
2115 if (isLoopBodyClosureOp(op))
2116 return true;
2117 // The next sequential loop may consume shared state produced by the prior
2118 // one.
2119 if (isa<scf::ForOp>(op))
2120 return true;
2121 if (scf::ParallelOp parallelOp = dyn_cast<scf::ParallelOp>(op)) {
2122 if (mlir::acc::hasParDimsAttr(parallelOp)) {
2123 if (mlir::acc::GPUParallelDimsAttr parDims =
2124 mlir::acc::getParDimsAttr(parallelOp)) {
2125 if (parDims.getArray().size() == 1 &&
2126 parDims.getArray().front().isSeq()) {
2127 return true;
2128 }
2129 }
2130 }
2131 }
2132 return false;
2133}
2134
2135/// True when a loop is followed by other work in the same block before the
2136/// loop body closes; the post-loop barrier must wait for that reconvergence
2137/// point instead of being placed right after the loop.
2138static bool hasTrailingSideEffectSiblings(Operation *loopOp) {
2139 for (Operation *next = loopOp->getNextNode(); next;
2140 next = next->getNextNode()) {
2141 return !isLoopBodyClosureOp(next);
2142 }
2143 return false;
2144}
2145
2146// Insert a barrier after a sequential loop when the surrounding parallel
2147// structure requires it, so that block threads observe the loop's writes to
2148// gang-/block-private shared memory before a later loop reads them. The barrier
2149// must land at an enclosing collective (block- or worker-level) point where all
2150// threads converge, so it cannot deadlock.
2151//
2152// The function walks the parent hierarchy of the loop to decide where (if at
2153// all) to place the barrier:
2154// - No enclosing parallel loop (top-level worksharing loop): emit a
2155// workgroup barrier when the loop writes shared memory and a later sibling
2156// loop may read it.
2157// - Nearest scf.parallel parent is itself sequential: a barrier *after* it
2158// would be unsafe when threads have varying iteration counts. However, when
2159// the loop has thread-level sub-loops collaborating on block-private memory
2160// (all threads participate every iteration), walk up to the block-level
2161// ancestor and insert the barrier there.
2162// - Nearest scf.parallel parent is a non-sequential parallel loop: walk up to
2163// the block-level (or worker/thread-y) ancestor and insert the barrier
2164// there, handling gang-redundant init loops and grid-stride remainders.
2165void ACCCGToGPULowering::createBarrierAfterSeqLoop(Operation *loopOp) {
2166 // Host loops enclosing the compute region are not GPU execution scopes.
2167 auto getParentParallel = [&](Operation *op) -> scf::ParallelOp {
2168 scf::ParallelOp parent = op->getParentOfType<scf::ParallelOp>();
2169 if (parent && computeRegion->isAncestor(parent))
2170 return parent;
2171 return {};
2172 };
2173 scf::ParallelOp wsLoop = getParentParallel(loopOp);
2174 if (!wsLoop) {
2175 // loopOp is a worksharing loop at the kernel-body top level (no enclosing
2176 // parallel loop). When it writes gang-private shared memory
2177 // that a later sibling loop reads, a workgroup barrier is needed between
2178 // them. The point just after a top-level loop is uniform (all threads reach
2179 // it), so a workgroup-wide barrier here cannot deadlock. Loops writing only
2180 // global/thread-private memory, or with no subsequent reader, get none.
2181 if (mayWriteSharedMemory(loopOp) && hasSubsequentLoopSibling(loopOp))
2182 emitGPUBarrierWorkgroup(rewriter, loopOp->getLoc());
2183 return;
2184 }
2185
2186 mlir::acc::GPUParallelDimsAttr wsParDims = mlir::acc::getParDimsAttr(wsLoop);
2187 bool parentIsSeq =
2188 wsParDims.getArray().size() == 1 && wsParDims.getArray().front().isSeq();
2189
2190 if (parentIsSeq) {
2191 // loopOp is nested inside a sequential parent loop.
2192 // When the loop contains thread-level sub-loops,
2193 // multiple threads collaborate on shared (block-private) memory
2194 // within each iteration. Insert a block-level barrier.
2195 bool hasThreadSubLoop = false;
2196 loopOp->walk([&](scf::ParallelOp innerPar) -> WalkResult {
2197 if (innerPar.getOperation() == loopOp)
2198 return WalkResult::advance();
2199 mlir::acc::GPUParallelDimsAttr dims = mlir::acc::getParDimsAttr(innerPar);
2200 for (auto d : dims.getArray()) {
2201 if (d.isThreadX() || d.isThreadY()) {
2202 hasThreadSubLoop = true;
2203 return WalkResult::interrupt();
2204 }
2205 }
2206 return WalkResult::advance();
2207 });
2208 if (!hasThreadSubLoop)
2209 return;
2210 scf::ParallelOp threadLoop = getParentParallel(wsLoop);
2211 if (!threadLoop)
2212 return;
2213 scf::ParallelOp blockLoop = getParentParallel(threadLoop);
2214 if (!blockLoop)
2215 return;
2216 mlir::acc::GPUParallelDimsAttr parDimsAttr =
2217 mlir::acc::getParDimsAttr(blockLoop);
2218 if (parDimsAttr.hasOnlyBlockLevel())
2219 createBarrier(loopOp->getLoc(), parDimsAttr);
2220 return;
2221 }
2222
2223 // Parent is a non-sequential parallel loop. Walk up to find the block-level
2224 // ancestor and insert a barrier there.
2225 scf::ParallelOp seqLoop = getParentParallel(wsLoop);
2226 if (!seqLoop) {
2227 // wsLoop is a worksharing loop directly under the compute region with no
2228 // gang ancestor: a gang-redundant init loop (e.g. a thread-level loop that
2229 // every gang runs to fill its own copy of gang-private shared memory). If
2230 // it writes gang-private (block-only) memory that a later sibling loop
2231 // reads, insert a workgroup barrier between them. The barrier sits just
2232 // after the top-level loop where all threads converge, so it cannot
2233 // deadlock.
2234 if (mayWriteSharedMemory(loopOp) && hasSubsequentLoopSibling(wsLoop))
2235 emitGPUBarrierWorkgroup(rewriter, loopOp->getLoc());
2236 return;
2237 }
2238 if (scf::ParallelOp outerParLoop = getParentParallel(seqLoop)) {
2239 mlir::acc::GPUParallelDimsAttr parDimsAttr =
2240 mlir::acc::getParDimsAttr(outerParLoop);
2241 if (parDimsAttr.hasOnlyBlockLevel()) {
2242 createBarrier(loopOp->getLoc(), parDimsAttr);
2243 } else if (parDimsAttr.hasOnlyThreadYLevel()) {
2244 createPerRowBarrier(loopOp->getLoc());
2245 } else if (parDimsAttr && parDimsAttr.isSeq()) {
2246 // outerParLoop is a sequential grid-stride remainder of a partitioned
2247 // gang loop, not the gang. Walk past the remainder(s) to the block-level
2248 // gang and barrier there.
2249 for (scf::ParallelOp gangLoop = getParentParallel(outerParLoop); gangLoop;
2250 gangLoop = getParentParallel(gangLoop)) {
2251 mlir::acc::GPUParallelDimsAttr gangDims =
2252 mlir::acc::getParDimsAttr(gangLoop);
2253 if (gangDims.hasOnlyBlockLevel()) {
2254 createBarrier(loopOp->getLoc(), gangDims);
2255 break;
2256 }
2257 if (!gangDims.isSeq())
2258 break;
2259 }
2260 }
2261 return;
2262 }
2263
2264 // No block-level ancestor above seqLoop: the gang loop is seqLoop itself, a
2265 // gang(+vector) loop directly under the compute region. The fixed-depth
2266 // lookup above misses it (issue: a gang+vector init loop that writes
2267 // gang-private shared memory must be followed by a barrier before another
2268 // loop reads it). Only needed when the loop writes such shared memory; loops
2269 // writing global/thread-private memory (e.g. a plain gang-vector saxpy) do
2270 // not need one here.
2271 mlir::acc::GPUParallelDimsAttr parDimsAttr =
2273 if (parDimsAttr.hasOnlyBlockLevel() && mayWriteSharedMemory(loopOp)) {
2274 createBarrier(loopOp->getLoc(), parDimsAttr);
2275 }
2276}
2277
2278bool ACCCGToGPULowering::mayWriteSharedMemory(Operation *loopOp) {
2279 bool found = false;
2280 loopOp->walk([&](memref::StoreOp storeOp) {
2281 // Trace the store target back to its backing acc.private_local through
2282 // view/cast/box ops, then check the privatization is gang-level.
2283 llvm::SmallVector<Value, 8> worklist{storeOp.getMemref()};
2284 llvm::SmallPtrSet<Value, 8> seen;
2285 while (!worklist.empty()) {
2286 Value v = worklist.pop_back_val();
2287 if (!seen.insert(v).second)
2288 continue;
2289 Operation *def = v.getDefiningOp();
2290 if (!def)
2291 continue;
2292 if (acc::PrivateLocalOp privateLocal =
2293 dyn_cast<acc::PrivateLocalOp>(def)) {
2294 acc::PrivatizeOp privatizeOp =
2295 getPrivatizeOp(privateLocal, computeRegion);
2296 // Only gang-level (block, no thread) private memory is a single copy
2297 // shared across the workgroup's threads, so a write needs a workgroup
2298 // barrier before another thread reads it. A [block_x, thread_x]
2299 // privatization is thread-private (one copy per thread); barriering on
2300 // it would deadlock when threads take different grid-stride iteration
2301 // counts.
2302 if (mlir::acc::GPUParallelDimsAttr parDims =
2303 privatizeOp.getParDimsAttr()) {
2304 bool hasBlock = false, hasThread = false;
2305 for (mlir::acc::GPUParallelDimAttr d : parDims.getArray()) {
2306 if (d.isAnyBlock())
2307 hasBlock = true;
2308 if (d.isThreadX() || d.isThreadY())
2309 hasThread = true;
2310 }
2311 if (hasBlock && !hasThread) {
2312 found = true;
2313 return WalkResult::interrupt();
2314 }
2315 }
2316 continue;
2317 }
2318 worklist.append(def->getOperands().begin(), def->getOperands().end());
2319 }
2320 return WalkResult::advance();
2321 });
2322 return found;
2323}
2324
2325/// True when \p memref is storage allocated inside \p scope, looking through
2326/// effect-free view and conversion ops. Such storage is created by the thread
2327/// that runs the code, so no other thread sees it.
2328static bool isAllocatedInside(Value memref, Operation *scope) {
2329 Value v = memref;
2330 while (Operation *def = v.getDefiningOp()) {
2331 if (!scope->isAncestor(def))
2332 return false;
2333 if (auto effectOp = dyn_cast<MemoryEffectOpInterface>(def))
2334 if (effectOp.getEffectOnValue<MemoryEffects::Allocate>(v))
2335 return true;
2336 if (!isMemoryEffectFree(def) || def->getNumOperands() == 0)
2337 return false;
2338 if (ViewLikeOpInterface viewLike = dyn_cast<ViewLikeOpInterface>(def))
2339 v = viewLike.getViewSource();
2340 else
2341 v = def->getOperand(0);
2342 }
2343 return false;
2344}
2345
2346/// True when \p op is a loop whose iterations run one after the other and are
2347/// repeated by every thread that reaches it.
2348static bool isRedundantSequentialLoop(Operation *op) {
2349 if (isa<scf::ForOp, scf::WhileOp>(op))
2350 return true;
2351 scf::ParallelOp par = dyn_cast<scf::ParallelOp>(op);
2352 if (!par)
2353 return false;
2354 mlir::acc::GPUParallelDimsAttr dims = mlir::acc::getParDimsAttr(par);
2355 return dims && !dims.getArray().empty() &&
2356 llvm::all_of(dims.getArray(), [](mlir::acc::GPUParallelDimAttr d) {
2357 return d.isSeq();
2358 });
2359}
2360
2361/// The value that names the storage \p memref refers to, found by looking
2362/// through effect-free view and conversion ops, or null when the storage cannot
2363/// be identified. Two accesses with different non-null roots refer to
2364/// different storage. The arguments of a sequential loop are not identified:
2365/// they can name different storage in different iterations (a buffer swap).
2366/// An input of the compute region is traced into the value it is passed from,
2367/// so that inputs that are views of the same storage have the same root.
2368static Value getStorageRoot(Value memref) {
2369 // Ops such as fir.declare only have effects on resources that are not
2370 // memory (e.g. debug info), so they do not hide the storage behind them.
2371 auto onlyNonMemoryEffects = [](Operation *op) {
2372 MemoryEffectOpInterface effectOp = dyn_cast<MemoryEffectOpInterface>(op);
2373 if (!effectOp)
2374 return false;
2375 SmallVector<MemoryEffects::EffectInstance> effects;
2376 effectOp.getEffects(effects);
2377 return llvm::all_of(effects, [](const MemoryEffects::EffectInstance &e) {
2378 return e.getResource() != SideEffects::DefaultResource::get();
2379 });
2380 };
2381 Value v = memref;
2382 while (true) {
2383 Operation *def = v.getDefiningOp();
2384 if (!def) {
2385 Operation *owner = cast<BlockArgument>(v).getOwner()->getParentOp();
2386 if (isa<scf::ForOp, scf::WhileOp>(owner))
2387 return Value();
2388 // The region cannot see where its inputs come from, but the values it is
2389 // passed may be views of the same storage. Keep the argument as the root
2390 // when that storage cannot be identified.
2391 if (auto computeOp = dyn_cast<acc::ComputeRegionOp>(owner))
2392 if (Value operand = computeOp.getOperand(cast<BlockArgument>(v)))
2393 if (Value outerRoot = getStorageRoot(operand))
2394 return outerRoot;
2395 return v;
2396 }
2397 if (auto effectOp = dyn_cast<MemoryEffectOpInterface>(def))
2398 if (effectOp.getEffectOnValue<MemoryEffects::Allocate>(v))
2399 return v;
2400 if ((!isMemoryEffectFree(def) && !onlyNonMemoryEffects(def)) ||
2401 def->getNumOperands() == 0)
2402 return Value();
2403 if (ViewLikeOpInterface viewLike = dyn_cast<ViewLikeOpInterface>(def))
2404 v = viewLike.getViewSource();
2405 else
2406 v = def->getOperand(0);
2407 }
2408}
2409
2410bool ACCCGToGPULowering::mayAccessSharedMemory(Operation *root, bool reads,
2411 bool writes, bool workerLevel,
2412 Operation *localScope,
2413 Operation *ignore,
2414 SharedStorage *collect,
2415 const SharedStorage *filter) {
2416 bool found = false;
2417 // Reports a shared access to \p target (null when unknown). Without
2418 // \p collect the walk stops here; with it the storage is recorded and the
2419 // walk goes on.
2420 auto sharedAccess = [&](Value target) {
2421 Value storage = target ? getStorageRoot(target) : Value();
2422 if (filter && storage && !filter->unknown &&
2423 !filter->roots.contains(storage))
2424 return WalkResult::advance();
2425 found = true;
2426 if (!collect)
2427 return WalkResult::interrupt();
2428 if (storage)
2429 collect->roots.insert(storage);
2430 else
2431 collect->unknown = true;
2432 return WalkResult::advance();
2433 };
2434 root->walk([&](Operation *op) {
2435 if (op->hasTrait<OpTrait::IsTerminator>())
2436 return WalkResult::advance();
2437 if (ignore && ignore->isAncestor(op))
2438 return WalkResult::advance();
2439 // Reductions combine their partial results with their own synchronization.
2440 if (isa<acc::ReductionAccumulateOp, acc::ReductionCombineOp,
2441 acc::ReductionCombineRegionOp>(op))
2442 return WalkResult::advance();
2443 MemoryEffectOpInterface effectOp = dyn_cast<MemoryEffectOpInterface>(op);
2444 if (!effectOp) {
2445 // Ops that only contain other ops are covered by the walk. Anything else
2446 // with unknown effects (e.g. a call) may access shared memory.
2447 if (op->hasTrait<OpTrait::HasRecursiveMemoryEffects>())
2448 return WalkResult::advance();
2449 return sharedAccess(Value());
2450 }
2451 SmallVector<MemoryEffects::EffectInstance> effects;
2452 effectOp.getEffects(effects);
2453 for (const MemoryEffects::EffectInstance &effect : effects) {
2454 bool relevant =
2455 (writes && isa<MemoryEffects::Write>(effect.getEffect())) ||
2456 (reads && isa<MemoryEffects::Read>(effect.getEffect()));
2457 if (!relevant)
2458 continue;
2459 Value target = effect.getValue();
2460 if (target) {
2461 PrivateMemScope scope = getPrivateScopeForMemref(target);
2462 if (scope == PrivateMemScope::Thread ||
2463 (workerLevel && scope == PrivateMemScope::Worker))
2464 continue;
2465 if (localScope && isAllocatedInside(target, localScope))
2466 continue;
2467 }
2468 if (sharedAccess(target).wasInterrupted())
2469 return WalkResult::interrupt();
2470 }
2471 return WalkResult::advance();
2472 });
2473 return found;
2474}
2475
2476bool ACCCGToGPULowering::needsBarrierAfterThreadLoop(scf::ParallelOp loop) {
2477 mlir::acc::GPUParallelDimsAttr loopDims = mlir::acc::getParDimsAttr(loop);
2478 if (!loopDims || loopDims.getArray().size() != 1)
2479 return false;
2480 mlir::acc::GPUParallelDimAttr loopDim = loopDims.getArray().front();
2481 if (!loopDim.isThreadX() && !loopDim.isThreadY())
2482 return false;
2483 bool workerLevel = loopDim.isThreadY();
2484
2485 // Inside a worker loop, createBarrierAfterSeqLoop already adds a per-row
2486 // barrier after the sequential remainder of each thread loop. Skip, to avoid
2487 // a repeat.
2488 for (Operation *parent = loop->getParentOp();
2489 parent && parent != computeRegion.getOperation();
2490 parent = parent->getParentOp()) {
2491 scf::ParallelOp parentLoop = dyn_cast<scf::ParallelOp>(parent);
2492 if (!parentLoop)
2493 continue;
2494 mlir::acc::GPUParallelDimsAttr parentDims =
2495 mlir::acc::getParDimsAttr(parentLoop);
2496 if (!parentDims)
2497 continue;
2498 for (mlir::acc::GPUParallelDimAttr dim : parentDims.getArray())
2499 if (dim.isThreadY())
2500 return false;
2501 }
2502
2503 // A loop that works on a shared-memory tile made for it (for instance by the
2504 // cache directive lowering) fills, uses and writes back that tile with its
2505 // own synchronization.
2506 bool hasOwnTile = false;
2507 loop->walk([&](acc::GPUSharedMemoryOp) {
2508 hasOwnTile = true;
2509 return WalkResult::interrupt();
2510 });
2511 if (hasOwnTile)
2512 return false;
2513
2514 // Outside a sequential nest the loop is reached once, and what follows it is
2515 // handled by the predication and loop-level barriers.
2516 bool inSequentialNest = false;
2517 for (Operation *parent = loop->getParentOp();
2518 parent && parent != computeRegion.getOperation();
2519 parent = parent->getParentOp()) {
2520 if (isa<scf::ForOp, scf::WhileOp>(parent)) {
2521 inSequentialNest = true;
2522 break;
2523 }
2524 }
2525 if (!inSequentialNest)
2526 return false;
2527
2528 // The iterations are spread over the threads, so a thread cannot rely on
2529 // what another thread did in the loop. Accesses to thread-private memory
2530 // never conflict. A later read conflicts with a write in the loop (read
2531 // after write) and a later write conflicts with a read (write after read) or
2532 // a write (write after write) in the loop, when both may refer to the same
2533 // storage.
2534 SharedStorage written, touched;
2535 mayAccessSharedMemory(loop, /*reads=*/false, /*writes=*/true, workerLevel,
2536 /*localScope=*/loop, /*ignore=*/nullptr, &written);
2537 mayAccessSharedMemory(loop, /*reads=*/true, /*writes=*/false, workerLevel,
2538 /*localScope=*/loop, /*ignore=*/nullptr, &touched);
2539 touched.insert(written);
2540 if (touched.empty())
2541 return false;
2542 bool loopWrites = !written.empty();
2543
2544 // True when \p op, executed after the loop, conflicts with it.
2545 auto conflictsWithLoop = [&](Operation *op, Operation *localScope,
2546 Operation *ignore) {
2547 if (loopWrites && mayAccessSharedMemory(
2548 op, /*reads=*/true, /*writes=*/false, workerLevel,
2549 localScope, ignore, /*collect=*/nullptr, &written))
2550 return true;
2551 return mayAccessSharedMemory(op, /*reads=*/false, /*writes=*/true,
2552 workerLevel, localScope, ignore,
2553 /*collect=*/nullptr, &touched);
2554 };
2555
2556 // Look for a conflicting access after the loop: later ops of every enclosing
2557 // block, and, for each enclosing loop, the ops in its body up to and
2558 // including the one that contains the loop, which run again in the next
2559 // iteration.
2560 for (Operation *cur = loop; cur && cur != computeRegion.getOperation();
2561 cur = cur->getParentOp()) {
2562 for (Operation *next = cur->getNextNode(); next; next = next->getNextNode())
2563 if (conflictsWithLoop(next, /*localScope=*/nullptr, /*ignore=*/nullptr))
2564 return true;
2565 Operation *parent = cur->getParentOp();
2566 if (!parent || parent == computeRegion.getOperation())
2567 break;
2568 if (!isRedundantSequentialLoop(parent))
2569 continue;
2570 // The condition and the other region of a while loop are not scanned.
2571 if (isa<scf::WhileOp>(parent))
2572 return true;
2573 // Scan the body up to and including cur. Accesses inside cur itself, which
2574 // contains the loop, also run again in the next iteration. Storage
2575 // allocated inside cur is private to it.
2576 for (Operation *prev = &cur->getBlock()->front(); prev;
2577 prev = prev->getNextNode()) {
2578 if (prev != cur) {
2579 if (conflictsWithLoop(prev, /*localScope=*/nullptr, /*ignore=*/nullptr))
2580 return true;
2581 continue;
2582 }
2583 // The loop reads again in the next iteration what other threads wrote in
2584 // this one (e.g. a double-buffered stencil whose only body op is the
2585 // loop). Its own writes are not treated as conflicting with its writes in
2586 // the next iteration: the loop is assumed to store the same elements from
2587 // the same threads each time.
2588 if (loopWrites && mayAccessSharedMemory(
2589 loop, /*reads=*/true, /*writes=*/false, workerLevel,
2590 /*localScope=*/cur,
2591 /*ignore=*/nullptr, /*collect=*/nullptr, &written))
2592 return true;
2593 // The other ops in cur run again too.
2594 if (cur != loop && conflictsWithLoop(cur, /*localScope=*/cur, loop))
2595 return true;
2596 break;
2597 }
2598 }
2599 return false;
2600}
2601
2602PrivateMemScope
2603ACCCGToGPULowering::getPrivateMemScope(acc::PrivatizeOp privatizeOp) {
2604 bool hasBlock = false;
2605 bool hasThreadX = false;
2606 bool hasThreadY = false;
2607 if (mlir::acc::GPUParallelDimsAttr parDims = privatizeOp.getParDimsAttr()) {
2608 for (mlir::acc::GPUParallelDimAttr d : parDims.getArray()) {
2609 if (d.isAnyBlock())
2610 hasBlock = true;
2611 if (d.isThreadX())
2612 hasThreadX = true;
2613 if (d.isThreadY())
2614 hasThreadY = true;
2615 }
2616 } else {
2617 for (mlir::acc::GPUParallelDimAttr d : computeRegion.getLaunchParDims())
2618 if (d.isAnyBlock())
2619 hasBlock = true;
2620 if (hasBlock)
2621 return PrivateMemScope::Gang;
2622 return PrivateMemScope::Thread;
2623 }
2624 if (hasThreadX)
2625 return PrivateMemScope::Thread;
2626 if (hasBlock && hasThreadY)
2627 return PrivateMemScope::Worker;
2628 if (hasBlock)
2629 return PrivateMemScope::Gang;
2630 return PrivateMemScope::Thread;
2631}
2632
2633/// Walks back from a memref use to its defining `acc.private_local`, if any.
2634static acc::PrivateLocalOp getPrivateLocalForMemref(Value memref) {
2635 llvm::SmallVector<Value, 8> worklist{memref};
2636 llvm::SmallPtrSet<Value, 8> seen;
2637 while (!worklist.empty()) {
2638 Value v = worklist.pop_back_val();
2639 if (!seen.insert(v).second)
2640 continue;
2641 Operation *def = v.getDefiningOp();
2642 if (!def)
2643 continue;
2644 if (acc::PrivateLocalOp privateLocal = dyn_cast<acc::PrivateLocalOp>(def))
2645 return privateLocal;
2646 getStorageSourceOperands(def, worklist);
2647 }
2648 return nullptr;
2649}
2650
2651PrivateMemScope ACCCGToGPULowering::getPrivateScopeForMemref(Value memref) {
2652 if (auto privateLocal = getPrivateLocalForMemref(memref))
2653 return getPrivateMemScope(getPrivatizeOp(privateLocal, computeRegion));
2654 return PrivateMemScope::None;
2655}
2656
2657acc::PrivatizeOp ACCCGToGPULowering::getPrivatizeForMemref(Value memref) {
2658 if (auto privateLocal = getPrivateLocalForMemref(memref))
2659 return getPrivatizeOp(privateLocal, computeRegion);
2660 return acc::PrivatizeOp();
2661}
2662
2663void ACCCGToGPULowering::collectSharedPrivateStores(
2664 Operation *root, llvm::SmallPtrSetImpl<Operation *> &gangPrivatizes,
2665 llvm::SmallPtrSetImpl<Operation *> &workerPrivatizes) {
2666 root->walk([&](memref::StoreOp storeOp) {
2667 PrivateMemScope scope = getPrivateScopeForMemref(storeOp.getMemref());
2668 if (scope != PrivateMemScope::Gang && scope != PrivateMemScope::Worker)
2669 return;
2670 acc::PrivatizeOp privatize = getPrivatizeForMemref(storeOp.getMemref());
2671 if (!privatize)
2672 return;
2673 if (scope == PrivateMemScope::Gang)
2674 gangPrivatizes.insert(privatize.getOperation());
2675 else
2676 workerPrivatizes.insert(privatize.getOperation());
2677 });
2678}
2679
2680bool ACCCGToGPULowering::isMatchingPrivateMemref(
2681 Value memref, PrivateMemScope storeScope,
2682 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes) {
2683 if (getPrivateScopeForMemref(memref) != storeScope)
2684 return false;
2685 acc::PrivatizeOp usePrivatize = getPrivatizeForMemref(memref);
2686 return usePrivatize && storePrivatizes.contains(usePrivatize.getOperation());
2687}
2688
2689bool ACCCGToGPULowering::hasParallelPrivateReuse(
2690 LoopLikeOpInterface seqLoopOp, Operation *skipOp,
2691 PrivateMemScope storeScope,
2692 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes) {
2693 if (storePrivatizes.empty())
2694 return false;
2695
2696 bool hasParallelPrivateUse = false;
2697 seqLoopOp.getOperation()->walk([&](Operation *op) {
2698 // Ignore loads inside the predicate.
2699 if (skipOp->isAncestor(op))
2700 return WalkResult::advance();
2701
2702 Value memref;
2703 if (memref::LoadOp loadOp = dyn_cast<memref::LoadOp>(op))
2704 memref = loadOp.getMemref();
2705 else if (memref::StoreOp storeOp = dyn_cast<memref::StoreOp>(op))
2706 memref = storeOp.getMemref();
2707 else
2708 return WalkResult::advance();
2709
2710 if (!isMatchingPrivateMemref(memref, storeScope, storePrivatizes))
2711 return WalkResult::advance();
2712
2713 bool insideNestedParallel = false;
2714 for (Operation *p = op->getParentOp(); p && p != seqLoopOp.getOperation();
2715 p = p->getParentOp()) {
2716 if (scf::ParallelOp par = dyn_cast<scf::ParallelOp>(p)) {
2717 if (mlir::acc::GPUParallelDimsAttr pd =
2719 if (llvm::any_of(pd.getArray(), [](mlir::acc::GPUParallelDimAttr d) {
2720 return !d.isSeq();
2721 })) {
2722 insideNestedParallel = true;
2723 break;
2724 }
2725 }
2726 }
2727 }
2728 if (!insideNestedParallel)
2729 return WalkResult::advance();
2730 // An inner parallel region uses the same private memory.
2731 hasParallelPrivateUse = true;
2732 return WalkResult::interrupt();
2733 });
2734
2735 return hasParallelPrivateUse;
2736}
2737
2738PrivateMemScope
2739ACCCGToGPULowering::needsPreStoreReuseBarrier(acc::PredicateRegionOp interOp) {
2740
2741 // Check if we need a pre-predicate barrier first.
2742 // Next, check if the barrier should be gang- or worker-level.
2743 LoopLikeOpInterface seqLoopOp = findFirstSequentialLoop(interOp);
2744 if (!seqLoopOp)
2745 return PrivateMemScope::None;
2746
2747 // Check if any op in the predicate region stores to gang- or worker-private
2748 // memory. If not, no barrier is needed.
2749 llvm::SmallPtrSet<Operation *, 4> gangPrivatizes, workerPrivatizes;
2750 collectSharedPrivateStores(interOp, gangPrivatizes, workerPrivatizes);
2751
2752 // A reused gang slot needs the workgroup barrier, which also reconverges the
2753 // worker rows, so look for that hazard first. A gang store whose slot is
2754 // never read back does not stand in for a worker one: fall through and check
2755 // the worker slots on their own, otherwise their per-row barrier is lost.
2756 if (hasParallelPrivateReuse(seqLoopOp, interOp, PrivateMemScope::Gang,
2757 gangPrivatizes))
2758 return PrivateMemScope::Gang;
2759 if (hasParallelPrivateReuse(seqLoopOp, interOp, PrivateMemScope::Worker,
2760 workerPrivatizes))
2761 return PrivateMemScope::Worker;
2762 return PrivateMemScope::None;
2763}
2764
2765bool ACCCGToGPULowering::needsInLoopReuseBarrier(Operation *loopOp) {
2766 // A sequential scf.parallel is the remainder of a partitioned gang loop: the
2767 // gang iterations this workgroup still runs as a grid stride. Its scalar
2768 // stores stay predicated and already reconverge between iterations, so the
2769 // reuse hole is the nested scf.for coming from `acc loop seq`.
2770 if (scf::ParallelOp par = dyn_cast<scf::ParallelOp>(loopOp))
2771 return false;
2772
2773 // The hazard needs a worker- or vector-level routine call in the body: every
2774 // workgroup thread reaches such a call and the callee synchronizes
2775 // internally, so threads leave it in no particular order and can then be
2776 // running different iterations of this loop at the same time.
2777 if (!hasThreadLevelRoutineCall)
2778 return false;
2779 bool callsThreadLevelRoutine = false;
2780 loopOp->walk([&](CallOpInterface callOp) -> WalkResult {
2781 if (mlir::acc::GPUParallelDimAttr parDim =
2782 getAccRoutineCallParDim(callOp, defaultPolicy)) {
2783 if (parDim.isThreadX() || parDim.isThreadY()) {
2784 callsThreadLevelRoutine = true;
2785 return WalkResult::interrupt();
2786 }
2787 }
2788 return WalkResult::advance();
2789 });
2790 if (!callsThreadLevelRoutine)
2791 return false;
2792
2793 // Only gang-level privatizations are a single copy shared by the whole
2794 // workgroup and reused by every iteration; worker- and thread-private copies
2795 // cannot be clobbered by another thread.
2796 llvm::SmallPtrSet<Operation *, 4> storedPrivatizes, workerPrivatizes;
2797 collectSharedPrivateStores(loopOp, storedPrivatizes, workerPrivatizes);
2798 if (storedPrivatizes.empty())
2799 return false;
2800
2801 // Storing alone is harmless: the next iteration only clobbers a value someone
2802 // still needs when the slot is read back in the body, either directly or by a
2803 // callee it is handed to.
2804 bool reusesGangPrivate = false;
2805 loopOp->walk([&](Operation *op) -> WalkResult {
2806 if (memref::LoadOp loadOp = dyn_cast<memref::LoadOp>(op))
2807 reusesGangPrivate = isMatchingPrivateMemref(
2808 loadOp.getMemref(), PrivateMemScope::Gang, storedPrivatizes);
2809 else if (CallOpInterface callOp = dyn_cast<CallOpInterface>(op))
2810 reusesGangPrivate = llvm::any_of(callOp.getArgOperands(), [&](Value arg) {
2811 return isMatchingPrivateMemref(arg, PrivateMemScope::Gang,
2812 storedPrivatizes);
2813 });
2814 return reusesGangPrivate ? WalkResult::interrupt() : WalkResult::advance();
2815 });
2816 if (!reusesGangPrivate)
2817 return false;
2818
2819 // A barrier inside the body is only safe when the whole workgroup runs every
2820 // iteration, so bail out under any thread-level worksharing loop, whose trip
2821 // count varies per thread.
2822 for (Operation *p = loopOp->getParentOp();
2823 p && p != computeRegion.getOperation(); p = p->getParentOp()) {
2824 scf::ParallelOp par = dyn_cast<scf::ParallelOp>(p);
2825 if (!par)
2826 continue;
2827 if (mlir::acc::GPUParallelDimsAttr parDims = mlir::acc::getParDimsAttr(par))
2828 for (mlir::acc::GPUParallelDimAttr d : parDims.getArray())
2829 if (d.isThreadX() || d.isThreadY())
2830 return false;
2831 }
2832 return true;
2833}
2834
2835void ACCCGToGPULowering::processPredicateRegion(
2836 acc::PredicateRegionOp interOp) {
2837 LLVM_DEBUG(llvm::dbgs() << "processing predicate region: ";
2838 interOp->print(llvm::dbgs()); llvm::dbgs() << "\n");
2839 Location loc = interOp->getLoc();
2840
2841 std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
2842 SmallVector<mlir::acc::GPUParallelDimAttr>>
2843 parDimsPair = computeActiveAndInactiveParDims(
2844 interOp, &interOp.getRegion().front());
2845 if (hasFailed)
2846 return;
2847
2848 // If ThreadY reduction exists, subgroup alignment is applied
2849 // (blockDim.x = subgroupSize), so ThreadX lanes exist even without explicit
2850 // ThreadX parallelism. Add ThreadX to inactiveParDims if not already present.
2851 // Exception: if this region contains a thread-level (vector or worker)
2852 // routine call, all ThreadX threads must reach the call so the routine's
2853 // workgroup-wide barriers (e.g. shared memory alloca sync) converge.
2854 // A single-thread worker launch is left unaligned, so it has no such lanes.
2855 if (hasThreadYReduction && !isSingleThreadWorkerLaunch()) {
2856 MLIRContext *ctx = computeRegion->getContext();
2857 mlir::acc::GPUParallelDimAttr threadXParDim =
2858 mlir::acc::GPUParallelDimAttr::threadXDim(ctx);
2859 bool hasThreadXInActive =
2860 llvm::any_of(parDimsPair.first, [](mlir::acc::GPUParallelDimAttr pd) {
2861 return pd.isThreadX();
2862 });
2863 bool hasThreadXInInactive =
2864 llvm::any_of(parDimsPair.second, [](mlir::acc::GPUParallelDimAttr pd) {
2865 return pd.isThreadX();
2866 });
2867
2868 // Check if THIS predicate region contains a thread-level routine call.
2869 // We use the pre-computed hasThreadLevelRoutineCall as an early-out
2870 // optimization.
2871 bool regionHasThreadLevelRoutineCall = false;
2872 if (hasThreadLevelRoutineCall) {
2873 interOp.getRegion().walk([&](CallOpInterface callOp) {
2874 if (mlir::acc::GPUParallelDimAttr parDim =
2875 getAccRoutineCallParDim(callOp, defaultPolicy)) {
2876 if (parDim.isThreadX() || parDim.isThreadY()) {
2877 regionHasThreadLevelRoutineCall = true;
2878 return WalkResult::interrupt();
2879 }
2880 }
2881 return WalkResult::advance();
2882 });
2883 }
2884
2885 if (!hasThreadXInActive && !hasThreadXInInactive &&
2886 !regionHasThreadLevelRoutineCall) {
2887 parDimsPair.second.push_back(threadXParDim);
2888 }
2889 }
2890
2891 Value predicate = emitPredicate(loc, parDimsPair.second);
2892 // With one thread per block nothing is predicated, but a block-level
2893 // reduction store below must still become a cross-block atomic.
2894 if (!predicate && llvm::all_of(computeRegion.getLaunchParDims(),
2895 [](mlir::acc::GPUParallelDimAttr pd) {
2896 return pd.isAnyBlock();
2897 }))
2898 predicate = arith::ConstantIntOp::create(rewriter, loc, 1, 1);
2899 if (predicate) {
2900 LLVM_DEBUG(llvm::dbgs() << "predicate: " << predicate << "\n");
2901 bool isInsideThreadXLoop = false;
2902 bool isInsideThreadYLoop = false;
2903 for (auto parDim : parDimsPair.first) {
2904 if (parDim.isThreadX())
2905 isInsideThreadXLoop = true;
2906 if (parDim.isThreadY())
2907 isInsideThreadYLoop = true;
2908 }
2909 // Emits the reconvergence barrier matching this region's predication level,
2910 // at the current insertion point. Called for both before and after the
2911 // predicated store. Below is the pre-predicate barrier; the post-predicate
2912 // barrier is emitted after the ifOp.
2913 auto emitReconvergenceBarrier = [&]() {
2914 if (isInsideThreadXLoop) {
2915 // Inside ThreadX loop - skip barrier
2916 } else if (isInsideThreadYLoop) {
2917 // Inside ThreadY loop
2918 if (!isInsideACCSpecializedRoutine(computeRegion)) {
2919 // Add barrier if ThreadX is predicated (lane 0 writes must be
2920 // visible to all lanes before they read).
2921 bool predicatesThreadX = llvm::any_of(
2922 parDimsPair.second,
2923 [](mlir::acc::GPUParallelDimAttr pd) { return pd.isThreadX(); });
2924 if (predicatesThreadX)
2925 createPerRowBarrier(loc);
2926 }
2927 // For acc routine ThreadY routines, skip barrier
2928 } else if (!parDimsPair.first.empty()) {
2929 // Inside block loop
2930 createBarrier(loc, mlir::acc::GPUParallelDimsAttr::get(
2931 interOp->getContext(), parDimsPair.first));
2932 } else {
2933 // Top level
2934 createBarrier(loc, mlir::acc::GPUParallelDimsAttr::get(
2935 interOp->getContext(), parDimsPair.second));
2936 }
2937 };
2938
2939 // A gang-level (block, no thread) shared slot written here and reused on
2940 // the next iteration of an enclosing sequential loop must not be
2941 // overwritten before all threads read the current value. Emit the
2942 // reconvergence barrier before the store too (the post-store barrier below
2943 // only orders this iteration's store->read). Restricted to the block-level
2944 // case: such loops are run uniformly by every workgroup thread, so the
2945 // workgroup barrier cannot deadlock; worker/vector (thread_y/thread_x)
2946 // loops may have divergent trip counts.
2947 PrivateMemScope scope = needsPreStoreReuseBarrier(interOp);
2948 if (scope == PrivateMemScope::Gang)
2949 emitGPUBarrierWorkgroup(rewriter, loc);
2950 else if (scope == PrivateMemScope::Worker)
2951 createPerRowBarrier(loc);
2952
2953 auto ifOp = scf::IfOp::create(rewriter, loc, predicate,
2954 /*withElseRegion=*/false);
2955 Region &thenRegion = ifOp.getThenRegion();
2956 Block &thenBlock = thenRegion.back();
2957 rewriter.setInsertionPoint(thenBlock.getTerminator());
2958 // Ops in a predicate region may need to be further processed, recurse
2959 for (auto &bodyOp : interOp.getRegion().front().getOperations()) {
2960 // If the store's value loads from a block-level reduction
2961 // memref, convert to atomic for cross-block correctness.
2962 // Only at kernel top level (no active thread dims).
2963 if (memref::StoreOp storeOp = dyn_cast<memref::StoreOp>(&bodyOp)) {
2964 std::optional<arith::AtomicRMWKind> blockReduceKind;
2965 bool failedReductionKind = false;
2966 Value storeVal = storeOp.getValueToStore();
2967 if (storeVal.getDefiningOp()) {
2968 // Walk the epilogue def-chain within the enclosing block to find
2969 // the block-level accumulate load feeding this store. Epilogue ops
2970 // (type conversions, arithmetic, etc.) are traversed transparently.
2971 // Non-acc loads and values defined outside the block are treated as
2972 // loop-invariant and return nullopt, bounding the search naturally.
2973 Block *epilogueBlock = interOp->getBlock();
2974 auto findBlockAccLoad =
2975 [&](auto &self,
2976 Value val) -> std::optional<arith::AtomicRMWKind> {
2977 Operation *def = val.getDefiningOp();
2978 if (!def || def->getBlock() != epilogueBlock)
2979 return std::nullopt;
2980 if (memref::LoadOp loadOp = dyn_cast<memref::LoadOp>(def)) {
2981 for (auto *user : loadOp.getMemRef().getUsers()) {
2982 if (acc::ReductionAccumulateOp accOp =
2983 dyn_cast<acc::ReductionAccumulateOp>(user)) {
2984 if (llvm::any_of(accOp.getParDims().getArray(),
2985 [](mlir::acc::GPUParallelDimAttr pd) {
2986 return pd.isAnyBlock();
2987 })) {
2988 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
2989 accOp.getReductionOperator(),
2990 accOp.getValue().getType(), accOp.getLoc());
2991 if (failed(kind)) {
2992 failedReductionKind = true;
2993 return std::nullopt;
2994 }
2995 return *kind;
2996 }
2997 }
2998 }
2999 return std::nullopt;
3000 }
3001 for (Value operand : def->getOperands())
3002 if (auto kind = self(self, operand))
3003 return kind;
3004 return std::nullopt;
3005 };
3006 blockReduceKind = findBlockAccLoad(findBlockAccLoad, storeVal);
3007 }
3008 if (failedReductionKind)
3009 return;
3010 // A private destination has a copy per block (or finer), so no other
3011 // block writes it and the store must stay a plain store.
3012 if (blockReduceKind && getPrivateScopeForMemref(storeOp.getMemref()) !=
3013 PrivateMemScope::None)
3014 blockReduceKind.reset();
3015 if (blockReduceKind) {
3016 Value input = mapping.lookupOrDefault(storeOp.getValueToStore());
3017 Value memref = mapping.lookupOrDefault(storeOp.getMemref());
3018 bool threadIsActive = llvm::any_of(
3019 parDimsPair.first, [](mlir::acc::GPUParallelDimAttr pd) {
3020 return !pd.isAnyBlock();
3021 });
3022 if (!threadIsActive &&
3023 !isa_and_nonnull<memref::AllocaOp>(
3024 unwrapMemRefConversion(memref).getDefiningOp())) {
3025 // Initialize the destination to the reduction identity before
3026 // cross-block atomics so that the final result reflects pure
3027 // assignment semantics (e.g. r = sum(a)), not accumulation
3028 // on top of the pre-kernel value.
3029 if (launch) {
3030 MemRefType memrefTy = cast<MemRefType>(memref.getType());
3031 // Map the store indices for ranked memrefs.
3032 SmallVector<Value> initIndices;
3033 for (Value idx : storeOp.getIndices())
3034 initIndices.push_back(mapping.lookupOrDefault(idx));
3035
3036 OpBuilder::InsertionGuard guard(rewriter);
3037 Block &launchBody = launch.getBody().front();
3038 Operation *insertBefore = nullptr;
3039
3040 launchBody.walk([&](scf::ParallelOp parOp) -> WalkResult {
3041 for (Operation *parent = parOp->getParentOp(); parent;
3042 parent = parent->getParentOp()) {
3043 if (parent == launch.getOperation())
3044 break;
3045 if (isa<scf::ParallelOp>(parent))
3046 return WalkResult::advance();
3047 }
3048 insertBefore = parOp.getOperation();
3049 return WalkResult::interrupt();
3050 });
3051 // The identity must be ordered before the atomics of every
3052 // block, so store it from a launch ahead of this one when the
3053 // address does not depend on the launch.
3054 std::function<bool(Value)> fromLaunch = [&](Value v) -> bool {
3055 if (auto arg = dyn_cast<BlockArgument>(v))
3056 return launch->isAncestor(arg.getOwner()->getParentOp());
3057 Operation *def = v.getDefiningOp();
3058 if (!launch->isAncestor(def) ||
3059 def->hasTrait<OpTrait::ConstantLike>())
3060 return false;
3061 // Ids and dims such as gpu.grid_dim take no operands.
3062 return def->getNumOperands() == 0 ||
3063 llvm::any_of(def->getOperands(), fromLaunch);
3064 };
3065 if (!fromLaunch(memref) &&
3066 llvm::none_of(initIndices, fromLaunch)) {
3067 rewriter.setInsertionPoint(launch);
3068 Value one = arith::ConstantIndexOp::create(rewriter, loc, 1);
3069 Value token = launch.getAsyncToken();
3070 auto initLaunch = gpu::LaunchOp::create(
3071 rewriter, loc, one, one, one, one, one, one,
3072 /*dynamicSharedMemorySize=*/nullptr,
3073 token ? token.getType() : Type(),
3074 launch.getAsyncDependencies());
3075 rewriter.setInsertionPointToStart(
3076 &initLaunch.getBody().front());
3077 rewriter.setInsertionPoint(
3078 gpu::TerminatorOp::create(rewriter, loc));
3079 } else if (insertBefore)
3080 rewriter.setInsertionPoint(insertBefore);
3081 else
3082 rewriter.setInsertionPointToStart(&launchBody);
3083 // Recursively re-materialize operations whose definitions
3084 // do not dominate the insertion point. A single-level clone
3085 // is insufficient when the value is produced by a chain of
3086 // operations (e.g. reinterpret_cast depending on box_dims,
3087 // divsi, convert, etc.) that are all defined after the
3088 // insertion point.
3089 DominanceInfo domInfo(launch);
3090 IRMapping initMapping;
3091 std::function<Value(Value)> materialize =
3092 [&](Value val) -> Value {
3093 Operation *defOp = val.getDefiningOp();
3094 if (!defOp)
3095 return val;
3096 if (domInfo.dominates(defOp, &*rewriter.getInsertionPoint()))
3097 return val;
3098 if (auto mapped = initMapping.lookupOrNull(val))
3099 return mapped;
3100 // Recurse on operands; the recursive call seeds
3101 // initMapping for any operand it clones, which the
3102 // subsequent rewriter.clone(..., initMapping) picks up.
3103 for (Value operand : defOp->getOperands())
3104 materialize(operand);
3105 Operation *cloned = rewriter.clone(*defOp, initMapping);
3106 for (auto [orig, clonedRes] :
3107 llvm::zip(defOp->getResults(), cloned->getResults())) {
3108 initMapping.map(orig, clonedRes);
3109 }
3110 return initMapping.lookup(val);
3111 };
3112 Value initMemref = materialize(memref);
3113 for (auto &idx : initIndices)
3114 idx = materialize(idx);
3115 Value identityVal = createIdentityValue(
3116 rewriter, loc, memrefTy.getElementType(), *blockReduceKind,
3117 /*useOnlyFiniteValue=*/true);
3118 Value blockId = gpu::BlockIdOp::create(
3119 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
3120 Value threadId = gpu::ThreadIdOp::create(
3121 rewriter, loc, rewriter.getIndexType(), gpu::Dimension::x);
3122 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
3123 Value isBlock0 = arith::CmpIOp::create(
3124 rewriter, loc, arith::CmpIPredicate::eq, blockId, zero);
3125 Value isThread0 = arith::CmpIOp::create(
3126 rewriter, loc, arith::CmpIPredicate::eq, threadId, zero);
3127 Value isFirstThread =
3128 arith::AndIOp::create(rewriter, loc, isBlock0, isThread0);
3129 auto initIf = scf::IfOp::create(rewriter, loc, isFirstThread,
3130 /*withElseRegion=*/false);
3131 rewriter.setInsertionPoint(
3132 initIf.getThenRegion().back().getTerminator());
3133 memref::StoreOp::create(rewriter, loc, identityVal, initMemref,
3134 initIndices);
3135 rewriter.setInsertionPointAfter(initIf);
3136 gpu::BarrierOp::create(rewriter, loc);
3137 }
3138 SmallVector<Value> atomicIndices;
3139 for (Value idx : storeOp.getIndices())
3140 atomicIndices.push_back(mapping.lookupOrDefault(idx));
3141 constructAtomicAccumulation(loc, memref, atomicIndices, input,
3142 *blockReduceKind);
3143 continue;
3144 }
3145 }
3146 }
3147 processOp(&bodyOp);
3148 }
3149 rewriter.setInsertionPointAfter(ifOp);
3150 emitReconvergenceBarrier();
3151 } else {
3152 // Ops in a predicate region may need to be further processed, recurse
3153 for (auto &bodyOp : interOp.getRegion().front().getOperations())
3154 processOp(&bodyOp);
3155 }
3156}
3157
3158// clang-format off
3159//
3160// Allocates private storage and broadcasts its pointer through a shared
3161// memref-of-memref slot, using the same predication utility as predicate
3162// regions.
3163//
3164// %0 = arith.cmpi eq, %thread_id_y, %c0 : index
3165// %1 = arith.cmpi eq, %thread_id_x, %c0 : index
3166// %2 = arith.andi %1, %0 : i1
3167// scf.if %2 {
3168// %alloc = memref.alloc() : memref<10xi32>
3169// memref.store %alloc, %arg1[] : memref<memref<10xi32>, #gpu.address_space<workgroup>>
3170// }
3171// gpu.barrier scope<subgroup>
3172// %4 = memref.load %arg1[] : memref<memref<10xi32>, #gpu.address_space<workgroup>>
3173//
3174// clang-format on
3175
3176Value ACCCGToGPULowering::allocatePrivatizeHeapStorage(
3177 acc::PrivatizeOp privatize, MemRefType baseTy,
3178 ValueRange mappedDynamicSizes) {
3179 Location loc = privatize.getLoc();
3180 Value mem =
3181 memref::AllocOp::create(rewriter, loc, baseTy, mappedDynamicSizes);
3182 recordGlobalMemory(privatize);
3183 OpBuilder::InsertionGuard guard(rewriter);
3184 Block *allocBlock = mem.getDefiningOp()->getBlock();
3185 if (allocBlock->mightHaveTerminator()) {
3186 rewriter.setInsertionPoint(allocBlock->getTerminator());
3187 memref::DeallocOp::create(rewriter, loc, mem);
3188 }
3189 mapping.map(privatize.getResult(), mem);
3190 // Ops inside the kernel are rewritten from scratch. If privatize is
3191 // outside the kernel, it must be replaced with the allocated storage.
3192 if (!privatize->getParentOfType<acc::ComputeRegionOp>())
3193 rewriter.replaceOp(privatize, mem);
3194 return mem;
3195}
3196
3197Value ACCCGToGPULowering::processPrivatize(acc::PrivatizeOp privatize) {
3198 LLVM_DEBUG(llvm::dbgs() << "processing privatize: ";
3199 privatize->print(llvm::dbgs()); llvm::dbgs() << "\n");
3200 Value tracked = privatize.getResult();
3201 if (acc::ComputeRegionOp insUser =
3202 dyn_cast<acc::ComputeRegionOp>(getOnlyUser(tracked))) {
3203 assert(privatize->hasOneUse() &&
3204 "expected acc.privatize op to have one use");
3205 tracked = insUser.getBody()->getArgument(
3206 privatize->use_begin()->getOperandNumber());
3207 }
3208 Operation *privatizeUser = getOnlyUser(tracked);
3209 assert(privatizeUser && "expected PrivateLocalOp user for privatize");
3210 acc::PrivateLocalOp privateLocalUser =
3211 dyn_cast<acc::PrivateLocalOp>(privatizeUser);
3212
3213 std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
3214 SmallVector<mlir::acc::GPUParallelDimAttr>>
3215 parDimsPair = computeActiveAndInactiveParDims(privatizeUser, nullptr);
3216 // Set `par_dims` only when this `acc.privatize` does not already carry it.
3217 if (!privatize.getParDimsAttr()) {
3218 privatize.setParDimsAttr(mlir::acc::GPUParallelDimsAttr::get(
3219 rewriter.getContext(), parDimsPair.first));
3220 }
3221
3222 Location loc = privatize->getLoc();
3223 acc::PrivateType privTy = cast<acc::PrivateType>(privatize.getType());
3224 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
3225 MemRefType baseTy = getPrivateBaseMemRefType(privTy.getBaseTy(), module);
3226
3227 gpu::GPUFuncOp gpuFuncOp = computeRegion->getParentOfType<gpu::GPUFuncOp>();
3228 // acc.privatize is outside this compute_region (e.g. passed via ins).
3229 // Leave the op unchanged here; processPrivateLocal materializes
3230 // storage when acc.private_local is lowered.
3231 if (!gpuFuncOp &&
3232 privatize->getParentOfType<acc::ComputeRegionOp>() != computeRegion) {
3233 return privatize.getResult();
3234 }
3235
3236 bool threadXActive =
3237 llvm::any_of(parDimsPair.first, [](mlir::acc::GPUParallelDimAttr parDim) {
3238 return parDim.isThreadX();
3239 });
3240 if (threadXActive &&
3241 canUseStackAlloca(baseTy, loc, options.maxThreadPrivateStack)) {
3242 auto alloca = memref::AllocaOp::create(rewriter, loc, baseTy);
3243 recordThreadPrivate(privateLocalUser);
3244 mapping.map(privatize.getResult(), alloca.getResult());
3245 return alloca.getResult();
3246 }
3247
3248 if (!gpuFuncOp)
3249 return privatize.getResult();
3250
3251 // When ThreadY is active, shared memory must be indexed by ThreadY ID to
3252 // avoid races between ThreadY threads.
3253 // For ThreadX acc routines, assume ThreadY may be active since the routine
3254 // can be called from a ThreadY loop at runtime.
3255 // For ThreadY/block acc routines, do not force ThreadY indexing - variables
3256 // outside the ThreadY loop should be shared across ThreadY threads.
3257 bool threadYIsActive =
3258 llvm::any_of(parDimsPair.first, [](mlir::acc::GPUParallelDimAttr parDim) {
3259 return parDim.isThreadY();
3260 });
3261 // For routines with multiple ThreadY threads, need a workgroup barrier
3262 // instead of a subgroup barrier.
3263 // - ThreadX routines: called independently by different ThreadY threads, need
3264 // per-ThreadY slots (override threadYIsActive)
3265 // - ThreadY routines: workgroup barrier, but respect parDimsPair for
3266 // threadYIsActive
3267 // (variables before ThreadY loop are shared, inside are per-ThreadY)
3268 // - Block routines: single call, ThreadY threads cooperate within the
3269 // routine, so
3270 // variables at routine level are shared across ThreadY threads (single
3271 // slot)
3272 bool needsWorkgroupBarrier = false;
3273 if (isInsideACCSpecializedRoutine(computeRegion)) {
3274 FunctionOpInterface funcOp =
3275 computeRegion->getParentOfType<FunctionOpInterface>();
3276 mlir::acc::GPUParallelDimAttr routineParDim =
3277 getSpecializedRoutineDim(funcOp, defaultPolicy);
3278 if (routineParDim.isThreadX()) {
3279 // ThreadX routine: always per-ThreadY slots since called from ThreadY
3280 // loops
3281 threadYIsActive = true;
3282 } else if (routineParDim.isThreadY()) {
3283 // ThreadY routine: workgroup barrier, but keep original threadYIsActive
3284 // (variables before ThreadY loop shared, inside per-ThreadY)
3285 needsWorkgroupBarrier = true;
3286 } else if (routineParDim.isAnyBlock()) {
3287 needsWorkgroupBarrier = true;
3288 }
3289 }
3290
3291 llvm::SmallVector<Value> mappedDynamicSizes;
3292 for (auto dynamicSize : privatize.getDynamicSizes()) {
3293 Value mappedDynamicSize = mapping.lookupOrDefault(dynamicSize);
3294 mappedDynamicSizes.push_back(mappedDynamicSize);
3295 }
3296 if (isInsideACCSpecializedRoutine(computeRegion) &&
3297 computeRegion.isEffectivelySerial()) {
3298 if (mappedDynamicSizes.empty()) {
3299 // Static sizes: use alloca (stack allocation)
3300 auto alloca =
3301 memref::AllocaOp::create(rewriter, privatize->getLoc(), baseTy);
3302 recordThreadPrivate(privateLocalUser);
3303 mapping.map(privatize.getResult(), alloca.getResult());
3304 return alloca.getResult();
3305 }
3306 // Dynamic sizes: use alloc (heap allocation) with dealloc
3307 return allocatePrivatizeHeapStorage(privatize, baseTy, mappedDynamicSizes);
3308 }
3309
3310 if (threadXActive) {
3311 // Reached only after canUseStackAlloca failed: either the static size is
3312 // over the per-thread stack budget, or the shape is dynamic so the size
3313 // is unknown. Heap-allocate in both cases so a large runtime extent
3314 // cannot overflow the stack. Each lane still owns its own copy.
3315 return allocatePrivatizeHeapStorage(privatize, baseTy, mappedDynamicSizes);
3316 }
3317
3318 // Predication - when threadYIsActive, don't predicate on ThreadY dimension
3319 // since each ThreadY needs to execute the allocation for its own slot
3320 SmallVector<mlir::acc::GPUParallelDimAttr> predicateDims;
3321 for (auto parDim : parDimsPair.second) {
3322 // Skip ThreadY if threadYIsActive - each ThreadY needs to allocate
3323 if (threadYIsActive && parDim.isThreadY())
3324 continue;
3325 predicateDims.push_back(parDim);
3326 }
3327 Value predicate = emitPredicate(loc, predicateDims);
3328 if (!predicate) {
3329 predicate = arith::ConstantOp::create(
3330 rewriter, loc, rewriter.getIntegerAttr(rewriter.getI1Type(), 1));
3331 }
3332 auto ifOp = scf::IfOp::create(rewriter, loc, predicate,
3333 /*withElseRegion=*/false);
3334 Region &thenRegion = ifOp.getThenRegion();
3335 Block &thenBlock = thenRegion.back();
3336 rewriter.setInsertionPoint(thenBlock.getTerminator());
3337 auto mem = memref::AllocOp::create(rewriter, privatize->getLoc(), baseTy,
3338 mappedDynamicSizes);
3339 recordGlobalMemory(privatize);
3340 // Shared memory allocation
3341 gpu::AddressSpaceAttr sharedMemoryAddressSpace = gpu::AddressSpaceAttr::get(
3342 computeRegion->getContext(), gpu::GPUDialect::getWorkgroupAddressSpace());
3343 // When ThreadY is active, create a shared memory array indexed by ThreadY ID.
3344 // Each ThreadY stores to its own slot; ThreadX lanes within a ThreadY share
3345 // it.
3346 constexpr int64_t kMaxThreadY = 32;
3347 MemRefType sharedMemTy =
3348 threadYIsActive
3349 ? MemRefType::get({kMaxThreadY}, baseTy, MemRefLayoutAttrInterface{},
3350 sharedMemoryAddressSpace)
3351 : MemRefType::get({}, baseTy, MemRefLayoutAttrInterface{},
3352 sharedMemoryAddressSpace);
3353 // The slot only transiently broadcasts the storage pointer, so reuse one per
3354 // type across privatizes, barriering (before the predicated store) on reuse.
3355 bool reuseBroadcast = !gpuFuncOp.isKernel();
3356 Value alloca;
3357 llvm::DenseMap<Type, Value>::iterator cachedSlot =
3358 reuseBroadcast ? privatizeBroadcastCache.find(sharedMemTy)
3359 : privatizeBroadcastCache.end();
3360 if (reuseBroadcast && cachedSlot != privatizeBroadcastCache.end()) {
3361 alloca = cachedSlot->second;
3362 OpBuilder::InsertionGuard guard(rewriter);
3363 rewriter.setInsertionPoint(ifOp);
3364 mlir::acc::GPUParallelDimAttr dim =
3365 needsWorkgroupBarrier
3366 ? mlir::acc::GPUParallelDimAttr::threadYDim(rewriter.getContext())
3367 : mlir::acc::GPUParallelDimAttr::threadXDim(rewriter.getContext());
3368 createBarrier(
3369 loc, mlir::acc::GPUParallelDimsAttr::get(rewriter.getContext(), {dim}));
3370 } else {
3371 alloca = gpuFuncOp.addWorkgroupAttribution(sharedMemTy,
3372 rewriter.getUnknownLoc());
3373 // Setting the alignment to 16 because of a bug in the gpu toolchain.
3374 // The default alignment is 8, but optimizations create a packed store of 16
3375 // bytes which cause a misalignment error at runtime.
3376 unsigned index = gpuFuncOp.getNumWorkgroupAttributions() - 1;
3377 gpuFuncOp.setWorkgroupAttributionAttr(index,
3378 LLVM::LLVMDialect::getAlignAttrName(),
3379 rewriter.getI32IntegerAttr(16));
3380 if (reuseBroadcast)
3381 privatizeBroadcastCache[sharedMemTy] = alloca;
3382 }
3383 // Store to shared memory, indexed by ThreadY ID when ThreadY is active.
3384 if (threadYIsActive) {
3385 Value threadYId = getThreadId(loc, gpu::Dimension::y);
3386 memref::StoreOp::create(rewriter, privatize->getLoc(), mem, alloca,
3387 ValueRange{threadYId});
3388 } else {
3389 memref::StoreOp::create(rewriter, privatize->getLoc(), mem, alloca);
3390 }
3391
3392 // Sync and load - use workgroup barrier for Block/ThreadY routines,
3393 // ThreadX barrier for ThreadX-only routines
3394 rewriter.setInsertionPointAfter(ifOp);
3395 if (needsWorkgroupBarrier) {
3396 mlir::acc::GPUParallelDimsAttr threadYDimsAttr =
3397 mlir::acc::GPUParallelDimsAttr::get(
3398 rewriter.getContext(),
3399 {mlir::acc::GPUParallelDimAttr::threadYDim(rewriter.getContext())});
3400 createBarrier(loc, threadYDimsAttr);
3401 } else {
3402 // ThreadX-only: use per-ThreadY barrier
3403 mlir::acc::GPUParallelDimsAttr threadXDimsAttr =
3404 mlir::acc::GPUParallelDimsAttr::get(
3405 rewriter.getContext(),
3406 {mlir::acc::GPUParallelDimAttr::threadXDim(rewriter.getContext())});
3407 createBarrier(loc, threadXDimsAttr);
3408 }
3409 // Load from shared memory, indexed by ThreadY ID when ThreadY is active.
3410 Value load;
3411 if (threadYIsActive) {
3412 Value threadYId = getThreadId(loc, gpu::Dimension::y);
3413 load = memref::LoadOp::create(rewriter, privatize->getLoc(), alloca,
3414 ValueRange{threadYId});
3415 } else {
3416 load = memref::LoadOp::create(rewriter, privatize->getLoc(), alloca,
3417 ValueRange{});
3418 }
3419 rewriter.setInsertionPointAfter(load.getDefiningOp());
3420 mapping.map(privatize.getResult(), load);
3421
3422 // Operations inside the kernel are all rewritten from scratch.
3423 // But if the privatize op is outside the kernel, it needs to be replaced.
3424 if (!privatize->getParentOfType<acc::ComputeRegionOp>())
3425 rewriter.replaceOp(privatize, load);
3426 // Deallocate
3427 rewriter.setInsertionPoint(ifOp->getBlock()->getTerminator());
3428 if (needsWorkgroupBarrier) {
3429 mlir::acc::GPUParallelDimsAttr workerDimsAttr =
3430 mlir::acc::GPUParallelDimsAttr::get(
3431 rewriter.getContext(),
3432 {mlir::acc::GPUParallelDimAttr::threadYDim(rewriter.getContext())});
3433 createBarrier(loc, workerDimsAttr);
3434 } else {
3435 mlir::acc::GPUParallelDimsAttr vectorDimsAttr =
3436 mlir::acc::GPUParallelDimsAttr::get(
3437 rewriter.getContext(),
3438 {mlir::acc::GPUParallelDimAttr::threadXDim(rewriter.getContext())});
3439 createBarrier(loc, vectorDimsAttr);
3440 }
3441 auto ifOp2 = scf::IfOp::create(rewriter, loc, predicate,
3442 /*withElseRegion=*/false);
3443 Region &thenRegion2 = ifOp2.getThenRegion();
3444 Block &thenBlock2 = thenRegion2.back();
3445 rewriter.setInsertionPoint(thenBlock2.getTerminator());
3446 memref::DeallocOp::create(rewriter, privatize->getLoc(), load);
3447
3448 // Return the private memory
3449 rewriter.setInsertionPointAfter(load.getDefiningOp());
3450
3451 return load;
3452}
3453
3454// Materialize acc.private_local storage from acc.privatize: per-thread alloca
3455// when possible, otherwise a shared broadcast slot or acc.gpu_shared_memory.
3456
3457void ACCCGToGPULowering::processPrivateLocal(
3458 acc::PrivateLocalOp privateLocal, std::optional<int64_t> sharedMemCopies) {
3459 LLVM_DEBUG(llvm::dbgs() << "processing private local: ";
3460 privateLocal->print(llvm::dbgs()); llvm::dbgs() << "\n");
3461 Location loc = privateLocal.getLoc();
3462 acc::PrivateType privTy =
3463 cast<acc::PrivateType>(privateLocal.getPrivatized().getType());
3464 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
3465 MemRefType baseTy = getPrivateBaseMemRefType(privTy.getBaseTy(), module);
3466 MemRefType byteMemrefTy =
3467 MemRefType::get({ShapedType::kDynamic}, rewriter.getI8Type());
3468
3469 acc::PrivatizeOp privatizeOp = getPrivatizeOp(privateLocal, computeRegion);
3470 Value inputMem;
3471 if (privatizeOp->getParentOfType<acc::ComputeRegionOp>() == computeRegion) {
3472 inputMem = mapping.lookupOrNull(privatizeOp);
3473 if (inputMem) {
3474 Value result = castPointerLikeTypeIfNeeded(rewriter, loc, inputMem,
3475 privateLocal.getType());
3476 mapping.map(privateLocal.getResult(), result);
3477 return;
3478 }
3479 } else {
3480 // Hoisted acc.privatize: allocate per-thread stack storage in the launch
3481 // body. Cross-thread array reduction accumulators are per-thread too, so
3482 // the accumulate can reduce each element across threads. Skip when storage
3483 // par_dims lack thread_x (gang-/worker-scoped array temp).
3484 acc::ReductionAccumulateArrayOp arrayAccum =
3485 perThreadArrayReductionAccum(privateLocal.getResult());
3486 if ((isThreadXPrivatize(privatizeOp) ||
3487 (arrayAccum && storageHasThreadX(privateLocal, computeRegion))) &&
3488 canUseStackAlloca(baseTy, loc, options.maxThreadPrivateStack)) {
3489 Value alloca = memref::AllocaOp::create(rewriter, loc, baseTy);
3490 recordThreadPrivate(privateLocal);
3491 if (arrayAccum) {
3492 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
3493 arrayAccum.getReductionOperator(), baseTy.getElementType(), loc);
3494 if (failed(kind))
3495 return;
3496 initPerThreadArrayAccum(rewriter, loc, alloca, baseTy, *kind);
3497 }
3498 Value mem = castPointerLikeTypeIfNeeded(rewriter, loc, alloca,
3499 privateLocal.getType());
3500 mapping.map(privateLocal.getResult(), mem);
3501 return;
3502 }
3503
3504 // If acc.privatize is outside the kernel, it needs to be converted
3505 // explicitly.
3506 std::optional<int64_t> copies =
3507 sharedMemCopies ? sharedMemCopies
3508 : isEligibleForSharedMemory(privateLocal, baseTy);
3509 if (copies) {
3510 int64_t numCopies = *copies;
3511 int64_t elementSize = getElementSizeInBytes(loc, baseTy.getElementType());
3512 int64_t numElements = 1;
3513 for (int64_t dim : baseTy.getShape())
3514 numElements *= dim;
3515 int64_t upperBound = elementSize * numElements * numCopies;
3516
3517 if (tryAllocateSharedMemory(upperBound)) {
3518 std::string varName =
3519 accSupport.getVariableName(privateLocal.getResult());
3520 sharedMemPrivateVarNames.push_back(varName.empty() ? "(*)" : varName);
3521
3522 gpu::AddressSpaceAttr workgroupAS = gpu::AddressSpaceAttr::get(
3523 computeRegion->getContext(),
3524 gpu::GPUDialect::getWorkgroupAddressSpace());
3525 MemRefType sharedMemTy =
3526 MemRefType::get(baseTy.getShape(), baseTy.getElementType(),
3527 MemRefLayoutAttrInterface{}, workgroupAS);
3528 Value sharedMem = acc::GPUSharedMemoryOp::create(
3529 rewriter, loc, sharedMemTy, rewriter.getI64IntegerAttr(numCopies),
3530 rewriter.getI64IntegerAttr(upperBound), ValueRange{}, IntegerAttr{},
3531 IntegerAttr{});
3532
3533 Value mem =
3534 castPointerLikeTypeIfNeeded(rewriter, loc, sharedMem, baseTy);
3535 Value result = castPointerLikeTypeIfNeeded(rewriter, loc, mem,
3536 privateLocal.getType());
3537
3538 mapping.map(privateLocal.getResult(), result);
3539 return;
3540 }
3541 }
3542
3543 OpBuilder::InsertionGuard guard(rewriter);
3544 rewriter.setInsertionPoint(privatizeOp);
3545 inputMem = processPrivatize(privatizeOp);
3546 }
3547
3548 if (isInsideACCSpecializedRoutine(computeRegion)) {
3549 assert(inputMem && "expected input mem to be mapped");
3550 Value result = castPointerLikeTypeIfNeeded(rewriter, loc, inputMem,
3551 privateLocal.getType());
3552 mapping.map(privateLocal.getResult(), result);
3553 return;
3554 }
3555
3556 // The private element shape augmented with a dimension for each level of
3557 // parallelism
3558 SmallVector<int64_t> viewShape;
3559 // The dynamic sizes of the view (num_gangs, num_workers, vector_length)
3560 SmallVector<Value> viewDynSizes;
3561 // The offset of the subview from gpu.block_id/gpu.thread_id dimensions.
3562 SmallVector<OpFoldResult> subviewOffset;
3563 // The sizes of the subview where the dimensionality is brought back to the
3564 // private element. That is size 1 for each active block/thread dimension.
3565 SmallVector<OpFoldResult> subviewSizes;
3566 // The strides of the subview
3567 SmallVector<int64_t> subviewStrides;
3568 // The shape of the subview
3569 SmallVector<int64_t> subviewShape;
3570
3571 std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
3572 SmallVector<mlir::acc::GPUParallelDimAttr>>
3573 parDimsPair = computeActiveAndInactiveParDims(privateLocal, nullptr);
3574 acc::ReductionAccumulateArrayOp arrayAccum =
3575 perThreadArrayReductionAccum(privateLocal.getResult());
3576 for (mlir::acc::GPUParallelDimAttr parDim : parDimsPair.first) {
3577 if ((parDim.isThreadX() ||
3578 (arrayAccum && storageHasThreadX(privateLocal, computeRegion))) &&
3579 canUseStackAlloca(baseTy, loc, options.maxThreadPrivateStack)) {
3580 Value alloca = memref::AllocaOp::create(rewriter, loc, baseTy);
3581 recordThreadPrivate(privateLocal);
3582 if (arrayAccum) {
3583 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
3584 arrayAccum.getReductionOperator(), baseTy.getElementType(), loc);
3585 if (failed(kind))
3586 return;
3587 initPerThreadArrayAccum(rewriter, loc, alloca, baseTy, *kind);
3588 }
3589 Value mem = castPointerLikeTypeIfNeeded(rewriter, loc, alloca,
3590 privateLocal.getType());
3591 mapping.map(privateLocal.getResult(), mem);
3592 return;
3593 }
3594 }
3595 if (parDimsPair.first.empty()) {
3596 // No parallelism is found above. It's single block execution.
3598 parDimsPair.first,
3599 mlir::acc::GPUParallelDimAttr::blockXDim(privateLocal.getContext()));
3600 }
3601 for (mlir::acc::GPUParallelDimAttr parDim : parDimsPair.first) {
3602 gpu::Processor gpuProc = parDim.getProcessor();
3603 Value gpuSize = getGPUSizeFor(gpuProc);
3604 viewDynSizes.push_back(gpuSize);
3605 viewShape.push_back(ShapedType::kDynamic);
3606 subviewOffset.push_back(getGPUThreadIdFor(gpuProc));
3607 subviewSizes.push_back(rewriter.getIndexAttr(1));
3608 }
3609
3610 SmallVector<Value> innerDynSizes =
3611 resolvePrivateLocalDynamicExtents(privateLocal);
3612
3613 unsigned dynIdx = 0;
3614 for (auto innerDim : baseTy.getShape()) {
3615 subviewOffset.push_back(rewriter.getIndexAttr(0));
3616 viewShape.push_back(innerDim);
3617 subviewShape.push_back(innerDim);
3618 if (innerDim == ShapedType::kDynamic) {
3619 assert(dynIdx < innerDynSizes.size() &&
3620 "not enough dynamic sizes for inner dimensions");
3621 viewDynSizes.push_back(innerDynSizes[dynIdx]);
3622 subviewSizes.push_back(innerDynSizes[dynIdx]);
3623 ++dynIdx;
3624 } else {
3625 subviewSizes.push_back(rewriter.getIndexAttr(innerDim));
3626 }
3627 }
3628
3629 // Do the strides in reverse order.
3630 int64_t stride = 1;
3631 for (auto innerDimIt = baseTy.getShape().rbegin();
3632 innerDimIt != baseTy.getShape().rend(); ++innerDimIt) {
3633 int64_t innerDim = *innerDimIt;
3634 subviewStrides.insert(subviewStrides.begin(), stride);
3635 if (innerDim == ShapedType::kDynamic)
3636 stride = ShapedType::kDynamic;
3637 if (stride != ShapedType::kDynamic)
3638 stride *= innerDim;
3639 }
3640
3641 Value memBuffer =
3642 castPointerLikeTypeIfNeeded(rewriter, loc, inputMem, byteMemrefTy);
3643 auto c0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
3644 MemRefType viewType = MemRefType::get(viewShape, baseTy.getElementType());
3645 auto view = memref::ViewOp::create(rewriter, loc, viewType, memBuffer,
3646 c0.getResult(), viewDynSizes);
3647
3648 // memref.subview
3649 StridedLayoutAttr stridedLayout = StridedLayoutAttr::get(
3650 computeRegion->getContext(), ShapedType::kDynamic, subviewStrides);
3651 MemRefType subviewType =
3652 MemRefType::get(subviewShape, baseTy.getElementType(), stridedLayout);
3653 SmallVector<OpFoldResult> ones(viewType.getRank(), rewriter.getIndexAttr(1));
3654 Value subview = memref::SubViewOp::create(rewriter, loc, subviewType, view,
3655 subviewOffset, subviewSizes, ones);
3656
3657 // Pointer-like casts cannot carry memref offsets. Shift the aligned pointer
3658 // so later zero-offset views retain this thread's private slice.
3659 auto metadata =
3660 memref::ExtractStridedMetadataOp::create(rewriter, loc, subview);
3661 Value elementBytes = arith::ConstantIndexOp::create(
3662 rewriter, loc, getElementSizeInBytes(loc, baseTy.getElementType()));
3663 Value byteOffset =
3664 arith::MulIOp::create(rewriter, loc, metadata.getOffset(), elementBytes);
3665 Value privateView = memref::ViewOp::create(rewriter, loc, baseTy, memBuffer,
3666 byteOffset, innerDynSizes);
3667 Value result = castPointerLikeTypeIfNeeded(rewriter, loc, privateView,
3668 privateLocal.getType());
3669 mapping.map(privateLocal.getResult(), result);
3670}
3671
3672// Could be scf::for or scf::parallel
3673template <typename LoopOp>
3674void ACCCGToGPULowering::processSeqLoop(LoopOp loopOp) {
3675 // Pre-process shared-memory-eligible private_local ops. Only direct-child
3676 // ops are considered; nested private_local ops (e.g. inside predicate_region)
3677 // are handled by recursive body processing.
3678 LLVM_DEBUG(llvm::dbgs() << "processing seq loop: ";
3679 loopOp->print(llvm::dbgs()); llvm::dbgs() << "\n");
3680 llvm::SmallPtrSet<Operation *, 4> preProcessedPrivateLocals;
3681 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
3682 for (auto &bodyOp : loopOp.getBody()->getOperations()) {
3683 if (acc::PrivateLocalOp privateLocal =
3684 dyn_cast<acc::PrivateLocalOp>(&bodyOp)) {
3685 acc::PrivateType privTy =
3686 cast<acc::PrivateType>(privateLocal.getPrivatized().getType());
3687 MemRefType baseTy = getPrivateBaseMemRefType(privTy.getBaseTy(), module);
3688 if (auto copies = isEligibleForSharedMemory(privateLocal, baseTy)) {
3689 processPrivateLocal(privateLocal, copies);
3690 preProcessedPrivateLocals.insert(privateLocal.getOperation());
3691 }
3692 }
3693 }
3694
3695 LoopOp newLoop =
3696 dyn_cast<LoopOp>(rewriter.cloneWithoutRegions(*loopOp, mapping));
3697 rewriter.createBlock(
3698 &newLoop.getRegion(), newLoop.getRegion().begin(),
3699 loopOp.getBody()->getArgumentTypes(),
3700 SmallVector<Location>(loopOp.getBody()->getArgumentTypes().size(),
3701 loopOp->getLoc()));
3702 rewriter.setInsertionPointToStart(&newLoop.getRegion().front());
3703
3704 // Need to clone all block arguments
3705 Block::BlockArgListType blockArgs = loopOp.getBody()->getArguments();
3706 assert(blockArgs.size() && "expected block arguments for loop");
3707 mapping.map(blockArgs, newLoop.getBody()->getArguments());
3708
3709 // A gang-private slot written here is one copy per workgroup, reused by every
3710 // iteration, and a thread that has already started the next iteration would
3711 // overwrite the value another thread has not read yet. Separate the
3712 // iterations with a barrier at the top of the body.
3713 if (needsInLoopReuseBarrier(loopOp.getOperation()) &&
3714 !isInsideConditional(rewriter.getInsertionBlock()))
3715 emitGPUBarrierWorkgroup(rewriter, loopOp->getLoc());
3716
3717 for (auto &bodyOp : loopOp.getBody()->getOperations()) {
3718 if (preProcessedPrivateLocals.contains(&bodyOp))
3719 continue;
3720 processOp(&bodyOp);
3721 }
3722
3723 mapping.map(loopOp.getResults(), newLoop.getResults());
3724 rewriter.setInsertionPointAfter(newLoop);
3725
3726 // Postpone the barrier when trailing work in this block still separates the
3727 // loop from the next reconvergence point.
3728 if (hasTrailingSideEffectSiblings(loopOp.getOperation()))
3729 deferredBarrierSeqLoops.push_back(loopOp.getOperation());
3730 else
3731 createBarrierAfterSeqLoop(loopOp.getOperation());
3732}
3733
3734void ACCCGToGPULowering::flushDeferredBarriersBefore(Operation *beforeOp) {
3735 Block *block = beforeOp->getBlock();
3736 SmallVector<Operation *, 4> toFlush;
3737 for (Operation *loopOp : deferredBarrierSeqLoops)
3738 if (loopOp->getBlock() == block && loopOp->isBeforeInBlock(beforeOp))
3739 toFlush.push_back(loopOp);
3740 if (toFlush.empty())
3741 return;
3742 llvm::sort(toFlush,
3743 [](Operation *a, Operation *b) { return a->isBeforeInBlock(b); });
3744 for (Operation *loopOp : toFlush)
3745 createBarrierAfterSeqLoop(loopOp);
3746 deferredBarrierSeqLoops.erase(
3747 std::remove_if(deferredBarrierSeqLoops.begin(),
3748 deferredBarrierSeqLoops.end(),
3749 [&](Operation *loopOp) {
3750 return loopOp->getBlock() == block &&
3751 loopOp->isBeforeInBlock(beforeOp);
3752 }),
3753 deferredBarrierSeqLoops.end());
3754}
3755
3756// try to process op as a loop mapped to a gpu parallelism
3757// failure signifies not a loop and needs different processing
3758void ACCCGToGPULowering::processParallelOp(scf::ParallelOp parallelOp) {
3759 LLVM_DEBUG(llvm::dbgs() << "processing par loop: ";
3760 parallelOp->print(llvm::dbgs()); llvm::dbgs() << "\n");
3761 assert(mlir::acc::hasParDimsAttr(parallelOp) &&
3762 "requires parallel dimensions attribute");
3763 mlir::acc::GPUParallelDimsAttr pDimsAttr =
3764 mlir::acc::getParDimsAttr(parallelOp);
3765 // both of these should be dealt with before compiler reaches ACCCGToGPU
3766 // Invalid parallel-loop structure should be rejected before acc-cg-to-gpu.
3767 assert(pDimsAttr.getArray().size() == 1 &&
3768 "expected a single par dim in acc-cg-to-gpu");
3769 assert(parallelOp.getInductionVars().size() == 1 &&
3770 "expected a single induction variable in acc-cg-to-gpu");
3771
3772 mlir::acc::GPUParallelDimAttr parDim = pDimsAttr.getArray().front();
3773
3774 bool savedGridStrideFlag = insideAccumulateGridStride;
3775 Value savedReductionBuf = reductionSharedBuf;
3776 if (parDim.isThreadX()) {
3777 bool found = false;
3778 parallelOp.getBody()->walk([&](acc::ReductionAccumulateOp accOp) {
3779 bool hasBlockDim = false;
3780 bool hasThreadDim = false;
3781 for (auto d : accOp.getParDims().getArray()) {
3782 if (d.isAnyBlock())
3783 hasBlockDim = true;
3784 if (d.isThreadX() || d.isThreadY())
3785 hasThreadDim = true;
3786 }
3787 if (hasThreadDim && !hasBlockDim) {
3788 found = true;
3789 return WalkResult::interrupt();
3790 }
3791 return WalkResult::advance();
3792 });
3793 if (found)
3794 insideAccumulateGridStride = true;
3795 }
3796
3797 // common loop body processing for both par0 and 1+
3798 auto processLoopBody = [&]() {
3799 // process inner ops recursively
3800 for (auto &bodyOp : parallelOp.getBody()->getOperations()) {
3801 if (bodyOp.hasTrait<OpTrait::IsTerminator>()) {
3802 // Non-cloned parallel loops reconverge at their terminator.
3803 flushDeferredBarriersBefore(&bodyOp);
3804 continue;
3805 }
3806 // Non-terminator body ops are processed recursively.
3807 processOp(&bodyOp);
3808 }
3809 };
3810
3811 if (parDim.isSeq()) {
3812 LLVM_DEBUG(llvm::dbgs() << "loop: parDim: " << parDim << " as gpu seq\n");
3813 // Sequential loops here are remainder loops from partitioned parallel
3814 // loops - clone them as-is but process the body as a parallel region.
3815 // When blockDim.x >= subgroupSize and the loop contains a thread-level
3816 // accumulate, inactive grid-stride threads cannot participate in subgroup
3817 // reductions, so we use atomic-to-shared-memory reduction instead.
3818 bool needsAtomicReduction = false;
3819 bool hasAccumulateSibling = false;
3820 if (scf::ParallelOp parentPar =
3821 parallelOp->getParentOfType<scf::ParallelOp>()) {
3822 if (mlir::acc::GPUParallelDimsAttr parentDims =
3823 mlir::acc::getParDimsAttr(parentPar);
3824 parentDims && llvm::any_of(parentDims.getArray(),
3825 [](auto d) { return d.isThreadX(); })) {
3826 for (auto &op : parentPar.getBody()->getOperations()) {
3827 if (acc::ReductionAccumulateOp acc =
3828 dyn_cast<acc::ReductionAccumulateOp>(op)) {
3829 bool hasBlockDim = false;
3830 bool hasThreadDim = false;
3831 for (auto d : acc.getParDims().getArray()) {
3832 if (d.isAnyBlock())
3833 hasBlockDim = true;
3834 if (d.isThreadX() || d.isThreadY())
3835 hasThreadDim = true;
3836 }
3837 if (hasThreadDim && !hasBlockDim)
3838 hasAccumulateSibling = true;
3839 }
3840 }
3841 }
3842 }
3843 if (insideAccumulateGridStride || hasAccumulateSibling) {
3844 for (auto launchArg : computeRegion.getLaunchArgs()) {
3845 if (acc::ParWidthOp pw = launchArg.getDefiningOp<acc::ParWidthOp>()) {
3846 if (pw.getParDim().isThreadX()) {
3847 if (auto cval = getConstantIntValue(pw.getLaunchArg()))
3848 needsAtomicReduction = (*cval >= options.subgroupSize);
3849 else
3850 needsAtomicReduction = true;
3851 break;
3852 }
3853 }
3854 }
3855 }
3856 if (needsAtomicReduction && !reductionSharedBuf) {
3857 Type elemTy;
3858 parallelOp.getBody()->walk([&](acc::ReductionAccumulateOp accOp) {
3859 Type t = accOp.getValue().getType();
3860 if (isa<FloatType, IntegerType>(t))
3861 elemTy = t;
3862 return elemTy ? WalkResult::interrupt() : WalkResult::advance();
3863 });
3864 if (!elemTy)
3865 needsAtomicReduction = false;
3866 }
3867 if (needsAtomicReduction && !reductionSharedBuf) {
3868 Location seqLoc = parallelOp->getLoc();
3869 gpu::AddressSpaceAttr workgroupAS = gpu::AddressSpaceAttr::get(
3870 computeRegion->getContext(),
3871 gpu::GPUDialect::getWorkgroupAddressSpace());
3872 Type elemTy;
3873 parallelOp.getBody()->walk([&](acc::ReductionAccumulateOp accOp) {
3874 Type t = accOp.getValue().getType();
3875 if (isa<FloatType, IntegerType>(t))
3876 elemTy = t;
3877 return elemTy ? WalkResult::interrupt() : WalkResult::advance();
3878 });
3879 assert(elemTy && "expected scalar reduction element type");
3880 unsigned elemBytes = elemTy.getIntOrFloatBitWidth() / 8;
3881 MemRefType bufTy = MemRefType::get({options.subgroupSize}, elemTy,
3882 AffineMap{}, workgroupAS);
3883 reductionSharedBuf = acc::GPUSharedMemoryOp::create(
3884 rewriter, seqLoc, bufTy, rewriter.getI64IntegerAttr(1),
3885 rewriter.getI64IntegerAttr(options.subgroupSize * elemBytes),
3886 ValueRange{}, IntegerAttr{}, IntegerAttr{});
3887 Value tidY = getThreadId(seqLoc, gpu::Dimension::y);
3888 Value identity;
3889 if (isa<FloatType>(elemTy)) {
3890 identity = arith::ConstantOp::create(
3891 rewriter, seqLoc, elemTy, rewriter.getFloatAttr(elemTy, 0.0));
3892 } else {
3893 identity = arith::ConstantIntOp::create(rewriter, seqLoc, elemTy, 0);
3894 }
3895 memref::StoreOp::create(rewriter, seqLoc, identity, reductionSharedBuf,
3896 tidY);
3897 createPerRowBarrier(seqLoc);
3898 }
3899 processSeqLoop(parallelOp);
3900 loopReductions.push_back(parallelOp);
3901 } else {
3902 LLVM_DEBUG(llvm::dbgs()
3903 << "processing loop: parDim: " << parDim << " as gpu par\n");
3904 // actual parallel loops get their iv mapped to gpu hierarchy
3905 // and the loop construct is not cloned to gpu kernel only the
3906 // ops are cloned with mapping of gpu id for original loop iv
3907 Value gpuThreadId = getGPUThreadIdFor(parDim.getProcessor());
3908 mapping.map(parallelOp.getInductionVars()[0], gpuThreadId);
3909
3910 processLoopBody();
3911
3912 // All threads of the row (or block) must finish their iterations before
3913 // any of them continues past the loop. The sequential nest around the loop
3914 // is executed by every thread, so without a barrier its later code can read
3915 // results that another thread has not stored yet.
3916 if (needsBarrierAfterThreadLoop(parallelOp))
3917 createBarrier(parallelOp->getLoc(), pDimsAttr);
3918
3919 // Since the loop is not copied over, create dummy mappings for_each
3920 // of the loop results. These will ultimately by replaced with a
3921 // reduction
3922 llvm::for_each(parallelOp.getResults(), [&](Value v) {
3923 Type valTy = v.getType();
3924 TypedAttr zeroAttr = rewriter.getZeroAttr(valTy);
3925 auto zero = arith::ConstantOp::create(rewriter, parallelOp->getLoc(),
3926 valTy, zeroAttr);
3927 mapping.map(v, zero);
3928 });
3929 loopReductions.push_back(parallelOp);
3930 }
3931 insideAccumulateGridStride = savedGridStrideFlag;
3932 if (!insideAccumulateGridStride && !savedReductionBuf)
3933 reductionSharedBuf = Value();
3934}
3935
3936/// Map an atomic RMW kind to the corresponding `gpu.all_reduce` operation.
3937static gpu::AllReduceOperation
3938getAllReduceOperation(arith::AtomicRMWKind kind) {
3939 switch (kind) {
3940 case arith::AtomicRMWKind::addf:
3941 case arith::AtomicRMWKind::addi:
3942 return gpu::AllReduceOperation::ADD;
3943 case arith::AtomicRMWKind::mulf:
3944 case arith::AtomicRMWKind::muli:
3945 return gpu::AllReduceOperation::MUL;
3946 case arith::AtomicRMWKind::minu:
3947 return gpu::AllReduceOperation::MINUI;
3948 case arith::AtomicRMWKind::mins:
3949 return gpu::AllReduceOperation::MINSI;
3950 case arith::AtomicRMWKind::minnumf:
3951 return gpu::AllReduceOperation::MINNUMF;
3952 case arith::AtomicRMWKind::maxu:
3953 return gpu::AllReduceOperation::MAXUI;
3954 case arith::AtomicRMWKind::maxs:
3955 return gpu::AllReduceOperation::MAXSI;
3956 case arith::AtomicRMWKind::maxnumf:
3957 return gpu::AllReduceOperation::MAXNUMF;
3958 case arith::AtomicRMWKind::ori:
3959 return gpu::AllReduceOperation::OR;
3960 case arith::AtomicRMWKind::andi:
3961 return gpu::AllReduceOperation::AND;
3962 case arith::AtomicRMWKind::xori:
3963 return gpu::AllReduceOperation::XOR;
3964 case arith::AtomicRMWKind::minimumf:
3965 return gpu::AllReduceOperation::MINIMUMF;
3966 case arith::AtomicRMWKind::maximumf:
3967 return gpu::AllReduceOperation::MAXIMUMF;
3968 case arith::AtomicRMWKind::assign:
3969 break;
3970 }
3971 llvm_unreachable("unsupported atomic kind");
3972}
3973
3974void ACCCGToGPULowering::constructAtomicAccumulation(
3975 Location loc, Value memref, ValueRange indices, Value input,
3976 arith::AtomicRMWKind kind) {
3977 assert(!memref.getDefiningOp<memref::AllocaOp>() &&
3978 "cannot lower atomic accumulation on an stack variable");
3979
3980 // acc.atomic.update derives the element address from the memref descriptor's
3981 // base pointer and offset field; it has no subscript operand. When the store
3982 // being lowered targets a specific array element (e.g. result(idx) =
3983 // max(...)), fold the indices into the descriptor offset with a subview so
3984 // the atomic updates the intended element. Otherwise the atomic always hits
3985 // element 0, so any reduction whose destination index is non-zero is
3986 // miscompiled (the result lands in element 0 while the intended element keeps
3987 // its identity-init value).
3988 Value target = memref;
3989 if (!indices.empty()) {
3990 MemRefType memrefTy = cast<MemRefType>(memref.getType());
3991 unsigned rank = memrefTy.getRank();
3992 assert(indices.size() == rank && "expected one index per memref dimension");
3993 SmallVector<OpFoldResult> offsets(indices.begin(), indices.end());
3994 SmallVector<OpFoldResult> sizes(rank, rewriter.getIndexAttr(1));
3995 SmallVector<OpFoldResult> strides(rank, rewriter.getIndexAttr(1));
3996 target = memref::SubViewOp::create(rewriter, loc, memref, offsets, sizes,
3997 strides);
3998 }
3999
4000 auto atomicUpdateOp =
4001 acc::AtomicUpdateOp::create(rewriter, loc, target, /*ifCond=*/Value());
4002 Region &region = atomicUpdateOp->getRegion(0);
4003 Block *block =
4004 rewriter.createBlock(&region, region.begin(), {input.getType()}, {loc});
4005 rewriter.setInsertionPointToStart(block);
4006 Value reductionExpr =
4007 generateReductionOp(rewriter, loc, input, block->getArgument(0), kind);
4008 acc::YieldOp::create(rewriter, loc, reductionExpr);
4009 rewriter.setInsertionPointAfter(atomicUpdateOp);
4010}
4011
4012void ACCCGToGPULowering::createGPUAllReduceOp(
4013 Location loc, Value input, Value memref, arith::AtomicRMWKind kind,
4014 mlir::acc::GPUParallelDimsAttr parDimsAttr, ValueRange indices,
4015 bool isPerThreadPrivateTarget) {
4016 gpu::AllReduceOperationAttr attr = gpu::AllReduceOperationAttr::get(
4017 computeRegion->getContext(), getAllReduceOperation(kind));
4018 auto emitAllReduce = [&](Value operand) -> Value {
4019 auto allReduceOp =
4020 gpu::AllReduceOp::create(rewriter, loc, operand, attr, true);
4021 mlir::acc::setParDimsAttr(allReduceOp, parDimsAttr);
4022 return allReduceOp;
4023 };
4024
4025 Value reducedValue;
4026 if (auto complexType = dyn_cast<ComplexType>(input.getType())) {
4027 // gpu.all_reduce takes only integers and floats, so a complex value has to
4028 // go through as components. Addition is the one operator reaching here
4029 // where that is equivalent: multiplication mixes the components, and
4030 // min/max have no ordering on complex at all.
4031 if (kind != arith::AtomicRMWKind::addf) {
4032 std::string msg;
4033 llvm::raw_string_ostream os(msg);
4034 os << "reduction: " << arith::stringifyAtomicRMWKind(kind) << " of "
4035 << complexType << " across threads";
4036 (void)accSupport.emitNYI(loc, os.str());
4037 hasFailed = true;
4038 return;
4039 }
4040 Type elementType = complexType.getElementType();
4041 Value realResult =
4042 emitAllReduce(complex::ReOp::create(rewriter, loc, elementType, input));
4043 Value imagResult =
4044 emitAllReduce(complex::ImOp::create(rewriter, loc, elementType, input));
4045 reducedValue = complex::CreateOp::create(rewriter, loc, complexType,
4046 realResult, imagResult);
4047 } else {
4048 reducedValue = emitAllReduce(input);
4049 }
4050 // Predicate the store on the thread-level dimensions being reduced so that
4051 // only one thread per reduced group writes the result. Only dimensions in
4052 // parDimsAttr are included; sweeping over all dimensions between the highest
4053 // par_dim and thread_x would incorrectly add unrelated dimensions (e.g.
4054 // thread_y for a thread_x-only reduction), preventing other rows from
4055 // storing their independent results.
4056 SmallVector<mlir::acc::GPUParallelDimAttr> inactiveParDims;
4057 MLIRContext *ctx = computeRegion->getContext();
4058 bool hasThreadX = false;
4059 for (auto parDim : parDimsAttr.getArray()) {
4060 if (parDim.isAnyBlock())
4061 continue;
4062 if (parDim.isThreadX())
4063 hasThreadX = true;
4064 if (computeRegion.getLaunchArg(parDim) ||
4065 isInsideACCSpecializedRoutine(computeRegion)) {
4066 inactiveParDims.push_back(parDim);
4067 }
4068 }
4069 // Subgroup alignment may introduce extra ThreadX lanes even when ThreadX is
4070 // not part of the reduction. Predicate on ThreadX so only one lane stores.
4071 // A single-thread worker launch is left unaligned, so it has no such lanes.
4072 if (!hasThreadX && !isSingleThreadWorkerLaunch())
4073 inactiveParDims.push_back(mlir::acc::GPUParallelDimAttr::threadXDim(ctx));
4074 Value predicate = emitPredicate(loc, inactiveParDims);
4075 // Predication is only needed when the store target is visible to
4076 // multiple threads (shared/global memory). Per-thread targets like
4077 // memref.alloca are thread-private: gpu.all_reduce returns the same
4078 // value on all threads, so each can safely store to its own copy.
4079 // Detect per-thread storage by walking through conversion ops to
4080 // find the underlying allocation.
4081 bool isPerThreadPrivate = isPerThreadPrivateTarget ||
4082 isa_and_nonnull<memref::AllocaOp>(
4083 unwrapMemRefConversion(memref).getDefiningOp());
4084 // combine
4085 scf::IfOp ifOp;
4086 if (predicate && !isPerThreadPrivate) {
4087 ifOp =
4088 scf::IfOp::create(rewriter, loc, predicate, /*withElseRegion=*/false);
4089 Region &thenRegion = ifOp.getThenRegion();
4090 Block &thenBlock = thenRegion.back();
4091 rewriter.setInsertionPoint(thenBlock.getTerminator());
4092 }
4093 memref::StoreOp::create(rewriter, loc, reducedValue, memref, indices);
4094 if (predicate && !isPerThreadPrivate)
4095 rewriter.setInsertionPointAfter(ifOp);
4096 // A later block combine reuses this instead of reloading the slot. This only
4097 // applies to scalar accumulators; array elements are indexed individually.
4098 if (indices.empty())
4099 reductionAccumValue[memref] = reducedValue;
4100}
4101
4102void ACCCGToGPULowering::postprocessAccumulateOp(
4103 acc::ReductionAccumulateOp op) {
4104 Location loc = op->getLoc();
4105
4106 rewriter.setInsertionPoint(op);
4107
4108 // Check whether this accumulate has only block-level par dims (no thread
4109 // dims). gpu.all_reduce reduces across threads within a block, which is
4110 // wrong for block-only reductions - the loop result is already per-thread
4111 // and only needs a predicated store to the memref.
4112 bool hasThreadDim = false;
4113 SmallVector<mlir::acc::GPUParallelDimAttr> threadParDims;
4114 for (auto parDim : op.getParDims().getArray()) {
4115 if (!parDim.isAnyBlock()) {
4116 hasThreadDim = true;
4117 threadParDims.push_back(parDim);
4118 }
4119 }
4120
4121 std::optional<arith::AtomicRMWKind> kind;
4122 if (hasThreadDim) {
4123 FailureOr<arith::AtomicRMWKind> kindOr = getReductionKind(
4124 op.getReductionOperator(), op.getValue().getType(), loc);
4125 if (failed(kindOr))
4126 return;
4127 kind = *kindOr;
4128 }
4129
4130 if (hasThreadDim && reductionSharedBuf &&
4131 op.getValue().getType() ==
4132 cast<MemRefType>(reductionSharedBuf.getType()).getElementType()) {
4133 Value val = op.getValue();
4134 Value mem = op.getMemref();
4135 Value tidY = getThreadId(loc, gpu::Dimension::y);
4136 memref::AtomicRMWOp::create(rewriter, loc, *kind, val, reductionSharedBuf,
4137 ValueRange{tidY});
4138 createPerRowBarrier(loc);
4139 Value result =
4140 memref::LoadOp::create(rewriter, loc, reductionSharedBuf, tidY);
4141 memref::StoreOp::create(rewriter, loc, result, mem);
4142 reductionAccumValue[mem] = result;
4143 } else if (hasThreadDim) {
4144 createGPUAllReduceOp(loc, op.getValue(), op.getMemref(), *kind,
4145 op.getParDims());
4146 // Nothing replaced the accumulate, so leave it in place rather than
4147 // erasing it below.
4148 if (hasFailed)
4149 return;
4150 } else {
4151 // Block-only: no gpu.all_reduce needed (all threads have the same
4152 // value after broadcast). Just store the value to the memref.
4153 // Predicate on all thread dims when the target is shared memory.
4154 Value val = mapping.lookupOrDefault(op.getValue());
4155 Value mem = mapping.lookupOrDefault(op.getMemref());
4156 bool isPerThreadPrivate = isa_and_nonnull<memref::AllocaOp>(
4157 unwrapMemRefConversion(mem).getDefiningOp());
4158 if (!isPerThreadPrivate) {
4159 SmallVector<mlir::acc::GPUParallelDimAttr> predDims;
4160 for (auto parDim : computeRegion.getLaunchParDims())
4161 if (!parDim.isAnyBlock())
4162 predDims.push_back(parDim);
4163 if (predDims.empty()) {
4164 predDims.push_back(mlir::acc::GPUParallelDimAttr::threadXDim(
4165 computeRegion->getContext()));
4166 }
4167 Value predicate = emitPredicate(loc, predDims);
4168 auto ifOp =
4169 scf::IfOp::create(rewriter, loc, predicate, /*withElseRegion=*/false);
4170 rewriter.setInsertionPoint(ifOp.getThenRegion().back().getTerminator());
4171 memref::StoreOp::create(rewriter, loc, val, mem);
4172 rewriter.setInsertionPointAfter(ifOp);
4173 } else {
4174 memref::StoreOp::create(rewriter, loc, val, mem);
4175 }
4176 }
4177
4178 // erase acc.reduction_accumulate
4179 rewriter.eraseOp(op);
4180}
4181
4182void ACCCGToGPULowering::postprocessLoopReduction(scf::ParallelOp parLoop) {
4183 if (parLoop.getNumReductions() == 0)
4184 return;
4185
4186 for (unsigned i = 0; i < parLoop.getNumResults(); ++i) {
4187 for (Operation *user :
4188 mapping.lookupOrDefault(parLoop.getResult(i)).getUsers()) {
4189 if (acc::ReductionAccumulateOp accumulateOp =
4190 dyn_cast<acc::ReductionAccumulateOp>(user)) {
4191 postprocessAccumulateOp(accumulateOp);
4192 }
4193 }
4194 }
4195}
4196
4197void ACCCGToGPULowering::processExecuteRegion(scf::ExecuteRegionOp op) {
4198 LLVM_DEBUG(llvm::dbgs() << "processing execute region op: ";
4199 op->print(llvm::dbgs()); llvm::dbgs() << "\n");
4200 Location loc = op->getLoc();
4201 auto types = op.getResultTypes();
4202 Region &oldRegion = op.getRegion();
4203 // create the executeRegion op inside gpu launch
4204 auto executeRegionOp = scf::ExecuteRegionOp::create(rewriter, loc, types);
4205 Region &region = executeRegionOp.getRegion();
4206 rewriter.createBlock(&region);
4207 rewriter.setInsertionPointToEnd(&region.front());
4208
4209 llvm::DenseMap<Block *, Block *> blockMap;
4210 blockMap[&oldRegion.front()] = &region.front();
4211
4212 // Create blocks in the new operation corresponding to all blocks in the
4213 // original op
4214 for (auto &oldBlock : llvm::drop_begin(oldRegion.getBlocks())) {
4215 TypeRange argTypes = oldBlock.getArgumentTypes();
4216 size_t numArgs = argTypes.size();
4217 // Create new block with same argument types
4218 Block *newBlock = rewriter.createBlock(&region, region.end(), argTypes,
4219 SmallVector<Location>(numArgs, loc));
4220 blockMap[&oldBlock] = newBlock;
4221 // Map block arguments
4222 mapping.map(oldBlock.getArguments(), newBlock->getArguments());
4223 }
4224
4225 // Iterate over all blocks of oldRegion and all operations inside them
4226 // process all the ops except the terminator
4227 for (auto [oldBlock, newBlock] :
4228 llvm::zip(oldRegion.getBlocks(), region.getBlocks())) {
4229 OpBuilder::InsertionGuard blockGuard(rewriter);
4230 rewriter.setInsertionPointToStart(&newBlock);
4231 for (auto &bodyOp : oldBlock.getOperations()) {
4232 // Skip terminators during normal iteration - handle them separately
4233 if (bodyOp.hasTrait<OpTrait::IsTerminator>())
4234 continue;
4235 processOp(&bodyOp);
4236 }
4237
4238 // Copy the terminator from old block to new block
4239 Operation *oldTerminator = oldBlock.getTerminator();
4240 rewriter.setInsertionPointToEnd(&newBlock);
4241 Operation *newTerminator = rewriter.clone(*oldTerminator, mapping);
4242
4243 // Replace successors with mapped blocks
4244 for (unsigned i = 0; i < oldTerminator->getNumSuccessors(); ++i) {
4245 Block *oldDest = oldTerminator->getSuccessor(i);
4246 Block *newDest = blockMap.lookup(oldDest);
4247 assert(newDest && "Successor block must be in blockMap");
4248 newTerminator->setSuccessor(newDest, i);
4249 }
4250 }
4251 mapping.map(op->getResults(), executeRegionOp->getResults());
4252 rewriter.setInsertionPointAfter(executeRegionOp);
4253}
4254
4255void ACCCGToGPULowering::processAccumulateOp(acc::ReductionAccumulateOp op) {
4256 LLVM_DEBUG(llvm::dbgs() << "processing accumulate op: " << *op << "\n");
4257 Value accumulateValue = op.getValue();
4258 if (reductionSharedBuf &&
4259 mapping.lookupOrDefault(accumulateValue).getType() ==
4260 cast<MemRefType>(reductionSharedBuf.getType()).getElementType()) {
4261 Location loc = op->getLoc();
4262 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
4263 op.getReductionOperator(), accumulateValue.getType(), loc);
4264 if (failed(kind))
4265 return;
4266 Value mappedValue = mapping.lookupOrDefault(accumulateValue);
4267 Value memref = mapping.lookupOrDefault(op.getMemref());
4268 Value tidY = getThreadId(loc, gpu::Dimension::y);
4269 memref::AtomicRMWOp::create(rewriter, loc, *kind, mappedValue,
4270 reductionSharedBuf, ValueRange{tidY});
4271 createPerRowBarrier(loc);
4272 Value result =
4273 memref::LoadOp::create(rewriter, loc, reductionSharedBuf, tidY);
4274 memref::StoreOp::create(rewriter, loc, result, memref);
4275 reductionAccumValue[memref] = result;
4276 return;
4277 }
4278 if (accumulateValue.getDefiningOp<scf::ParallelOp>()) {
4279 Operation *newOp = rewriter.clone(*op, mapping);
4280 mapping.map(op->getResults(), newOp->getResults());
4281 } else if (isRedundantChainAccumulate(op)) {
4282 // The destination memref already holds the correctly aggregated value
4283 // (atomically reduced by a preceding acc.reduction_combine with a block
4284 // par_dim). Skip the redundant gpu.all_reduce + atomic.update; emit a
4285 // Workgroup-wide barrier so downstream readers see all prior atomic
4286 // updates.
4287 LLVM_DEBUG(llvm::dbgs() << " skipped: redundant chain accumulate\n");
4288 gpu::BarrierOp::create(rewriter, op->getLoc());
4289 } else {
4290 Value mappedValue = mapping.lookupOrDefault(accumulateValue);
4291 Value memref = mapping.lookupOrDefault(op.getMemref());
4292 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
4293 op.getReductionOperator(), accumulateValue.getType(), op.getLoc());
4294 if (failed(kind))
4295 return;
4296 createGPUAllReduceOp(op->getLoc(), mappedValue, memref, *kind,
4297 op.getParDims());
4298 }
4299}
4300
4301/// True when \p v takes a distinct value per thread: it derives from a thread
4302/// id, either directly or through the bounds of an enclosing loop. By this
4303/// point a thread-mapped loop carries its mapping in its bounds rather than in
4304/// `acc.par_dims`, so the bounds are what must be inspected.
4305static bool isThreadVarying(Value v, ArrayRef<Value> threadIds,
4306 DenseSet<Value> &visited) {
4307 if (!v || !visited.insert(v).second)
4308 return false;
4309 if (llvm::is_contained(threadIds, v))
4310 return true;
4311 if (auto arg = dyn_cast<BlockArgument>(v)) {
4312 Operation *owner = arg.getOwner()->getParentOp();
4313 unsigned dim = arg.getArgNumber();
4314 if (auto loop = dyn_cast<scf::ParallelOp>(owner)) {
4315 if (dim >= loop.getLowerBound().size())
4316 return false;
4317 return isThreadVarying(loop.getLowerBound()[dim], threadIds, visited) ||
4318 isThreadVarying(loop.getStep()[dim], threadIds, visited);
4319 }
4320 if (auto loop = dyn_cast<scf::ForOp>(owner))
4321 return dim == 0 &&
4322 (isThreadVarying(loop.getLowerBound(), threadIds, visited) ||
4323 isThreadVarying(loop.getStep(), threadIds, visited));
4324 return false;
4325 }
4326 Operation *def = v.getDefiningOp();
4327 if (!def)
4328 return false;
4329 if (isa<gpu::ThreadIdOp, gpu::LaneIdOp>(def))
4330 return true;
4331 return llvm::any_of(def->getOperands(), [&](Value o) {
4332 return isThreadVarying(o, threadIds, visited);
4333 });
4334}
4335
4336/// Strips view and memory-space-cast chains to the underlying buffer.
4337static Value accumulatorRoot(Value v) {
4338 while (Operation *op = v.getDefiningOp()) {
4339 if (auto cast = dyn_cast<memref::MemorySpaceCastOp>(op)) {
4340 v = cast.getSource();
4341 continue;
4342 }
4343 if (auto viewLike = dyn_cast<ViewLikeOpInterface>(op)) {
4344 if (isa<MemRefType>(viewLike.getViewSource().getType())) {
4345 v = viewLike.getViewSource();
4346 continue;
4347 }
4348 }
4349 break;
4350 }
4351 return v;
4352}
4353
4354/// Matches `%l = load %m[%i]` / `%c = combine(%l, %x)` / `store %c, %m[%i]` on
4355/// the accumulator \p accum and returns the contributed value `%x`.
4356static Value matchAccumulatorUpdate(memref::StoreOp store, Value accum) {
4357 if (accumulatorRoot(store.getMemRef()) != accum)
4358 return {};
4359 Operation *combine = store.getValueToStore().getDefiningOp();
4360 if (!combine || combine->getNumOperands() != 2)
4361 return {};
4362 for (unsigned i = 0; i != 2; ++i) {
4363 auto load = combine->getOperand(i).getDefiningOp<memref::LoadOp>();
4364 if (!load || accumulatorRoot(load.getMemRef()) != accum)
4365 continue;
4366 if (!llvm::equal(load.getIndices(), store.getIndices()))
4367 continue;
4368 return combine->getOperand(1 - i);
4369 }
4370 return {};
4371}
4372
4373/// A block-shared accumulator is updated in place by the loop body, so several
4374/// threads may hit the same element. Make those updates atomic unless the
4375/// element index provably varies across the participating threads.
4376static void atomicizeSharedAccumulatorUpdates(Value accum,
4377 arith::AtomicRMWKind kind,
4378 ArrayRef<Value> threadIds,
4379 RewriterBase &rewriter) {
4380 OpBuilder::InsertionGuard guard(rewriter);
4381 SmallVector<memref::StoreOp> stores;
4382 SmallVector<Value> worklist{accum};
4383 DenseSet<Value> seen;
4384 while (!worklist.empty()) {
4385 Value cur = worklist.pop_back_val();
4386 if (!seen.insert(cur).second)
4387 continue;
4388 for (Operation *user : cur.getUsers()) {
4389 if (auto store = dyn_cast<memref::StoreOp>(user))
4390 stores.push_back(store);
4391 else if (isa<ViewLikeOpInterface, memref::MemorySpaceCastOp>(user))
4392 llvm::append_range(worklist, user->getResults());
4393 }
4394 }
4395
4396 for (memref::StoreOp store : stores) {
4397 Value contribution = matchAccumulatorUpdate(store, accum);
4398 if (!contribution)
4399 continue;
4400 // A thread-varying index means each thread owns its element, so the
4401 // existing plain update is already race-free.
4402 if (llvm::any_of(store.getIndices(), [&](Value idx) {
4403 DenseSet<Value> visited;
4404 return isThreadVarying(idx, threadIds, visited);
4405 }))
4406 continue;
4407 Operation *combine = store.getValueToStore().getDefiningOp();
4408 rewriter.setInsertionPoint(store);
4409 memref::AtomicRMWOp::create(rewriter, store.getLoc(), kind, contribution,
4410 store.getMemRef(), store.getIndices());
4411 rewriter.eraseOp(store);
4412 if (combine && combine->use_empty())
4413 rewriter.eraseOp(combine);
4414 }
4415}
4416
4417void ACCCGToGPULowering::processAccumulateArrayOp(
4418 acc::ReductionAccumulateArrayOp op) {
4419 LLVM_DEBUG(llvm::dbgs() << "processing accumulate array op: " << *op << "\n");
4420 Location loc = op.getLoc();
4421
4422 Value memref = mapping.lookupOrDefault(op.getMemref());
4423 MemRefType memrefTy = dyn_cast<MemRefType>(memref.getType());
4424 if (!memrefTy) {
4425 (void)accSupport.emitNYI(loc, "reduction: non-MemRefTy accumulate array");
4426 return;
4427 }
4428 FailureOr<arith::AtomicRMWKind> kindOr = getReductionKind(
4429 op.getReductionOperator(), memrefTy.getElementType(), loc);
4430 if (failed(kindOr))
4431 return;
4432 arith::AtomicRMWKind kind = *kindOr;
4433
4434 // The (already mapped/cloned) acc.bounds op describes the element range; it
4435 // is dead after lowering since we read its operands directly.
4436 acc::DataBoundsOp boundsOp = mapping.lookupOrDefault(op.getBounds())
4437 .getDefiningOp<acc::DataBoundsOp>();
4438 assert(boundsOp && "expected acc.bounds defining op for array accumulate");
4439 auto eraseDeadBounds = [&] {
4440 if (boundsOp->use_empty())
4441 rewriter.eraseOp(boundsOp);
4442 };
4443
4444 auto isUnitExtent = [&](mlir::acc::GPUParallelDimAttr parDim) {
4445 std::optional<uint64_t> width =
4446 computeRegion.getKnownConstantLaunchArg(parDim);
4447 return width && *width == 1;
4448 };
4449
4450 // A dimension launched one wide partitions nothing, so skip it.
4451 bool hasThreadDim = false;
4452 for (auto pd : op.getParDims().getArray()) {
4453 if (isUnitExtent(pd))
4454 continue;
4455 hasThreadDim |= pd.isAnyThread();
4456 }
4457
4458 // Without a thread dimension no two threads share an accumulator copy, so
4459 // each copy already holds a complete total and nothing has to be merged
4460 // here. Merging across gangs, if any, is left to the combine.
4461 if (!hasThreadDim) {
4462 eraseDeadBounds();
4463 return;
4464 }
4465
4466 // Per-element gpu.all_reduce is only correct when each thread owns its own
4467 // accumulator copy. For a statically-shaped accumulator, classify from the
4468 // operand: an explicit shared/heap allocation is block-shared regardless of
4469 // size, and a stack alloca (or a view over one) is per-thread when it fits
4470 // the per-thread stack budget. Storage `acc.par_dims` without thread_x means
4471 // gang-/worker-scoped privacy (shared among vector lanes) even if the type
4472 // would fit on the stack. For a dynamically-shaped accumulator the type
4473 // conveys no size, so classify from storage/accumulate thread_x dims.
4474 auto storageIsThreadXPrivate = [&](Value v) -> bool {
4475 acc::PrivateLocalOp privateLocal = getPrivateLocalForMemref(v);
4476 GPUParallelDimsAttr dims =
4477 privateLocal ? getPrivateParDims(privateLocal, computeRegion)
4478 : GPUParallelDimsAttr();
4479 if (!dims) {
4480 if (Operation *root = unwrapMemRefConversion(v).getDefiningOp())
4481 dims = getParDimsAttr(root);
4482 }
4483 return !dims ||
4484 llvm::any_of(dims.getArray(), [](auto d) { return d.isThreadX(); });
4485 };
4486 Operation *rootOp = unwrapMemRefConversion(memref).getDefiningOp();
4487 bool isSharedStorage = isa_and_nonnull<memref::AllocOp>(rootOp) ||
4488 isa_and_nonnull<acc::GPUSharedMemoryOp>(rootOp);
4489 if (auto addrSpace = dyn_cast_if_present<gpu::AddressSpaceAttr>(
4490 memrefTy.getMemorySpace())) {
4491 isSharedStorage |=
4492 addrSpace.getValue() == gpu::GPUDialect::getWorkgroupAddressSpace();
4493 }
4494 bool isPerThreadPrivate =
4495 !isSharedStorage && storageIsThreadXPrivate(op.getMemref()) &&
4496 (memrefTy.hasStaticShape()
4497 ? canUseStackAlloca(memrefTy, loc, options.maxThreadPrivateStack)
4498 : llvm::any_of(op.getParDims().getArray(),
4499 [](mlir::acc::GPUParallelDimAttr d) {
4500 return d.isThreadX();
4501 }));
4502 if (!isPerThreadPrivate) {
4503 // Block-shared accumulator: the body already updated it in place, so the
4504 // block partial is complete and the atomic combine finishes across blocks.
4505 // Threads that share an element must not race, so their in-place updates
4506 // become atomic.
4507 SmallVector<Value> threadIds;
4508 if (Value xId = getGPUThreadIdFor(gpu::Processor::ThreadX))
4509 threadIds.push_back(xId);
4510 if (Value yId = getGPUThreadIdFor(gpu::Processor::ThreadY))
4511 threadIds.push_back(yId);
4512 if (Value zId = getGPUThreadIdFor(gpu::Processor::ThreadZ))
4513 threadIds.push_back(zId);
4514 atomicizeSharedAccumulatorUpdates(accumulatorRoot(memref), kind, threadIds,
4515 rewriter);
4516 eraseDeadBounds();
4517 return;
4518 }
4519
4520 // Bounds are normalized to be zero-based.
4521 auto toIndex = [&](Value v) -> Value {
4522 if (v.getType().isIndex())
4523 return v;
4524 return arith::IndexCastOp::create(rewriter, loc, rewriter.getIndexType(),
4525 v);
4526 };
4527
4528 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
4529 Value one = arith::ConstantIndexOp::create(rewriter, loc, 1);
4530 Value lb =
4531 boundsOp.getLowerbound() ? toIndex(boundsOp.getLowerbound()) : zero;
4532 Value step = boundsOp.getStride() ? toIndex(boundsOp.getStride()) : one;
4533 // Exclusive upper bound. `extent` counts elements, so the span is
4534 // `extent * step` (for the common unit-stride case step is 1); fall back to
4535 // the inclusive upperbound when no extent is given.
4536 Value ub;
4537 if (boundsOp.getExtent()) {
4538 Value span = arith::MulIOp::create(rewriter, loc,
4539 toIndex(boundsOp.getExtent()), step);
4540 ub = arith::AddIOp::create(rewriter, loc, lb, span);
4541 } else {
4542 assert(boundsOp.getUpperbound() &&
4543 "acc.bounds must specify an extent or upperbound");
4544 ub = arith::AddIOp::create(rewriter, loc, toIndex(boundsOp.getUpperbound()),
4545 one);
4546 }
4547
4548 // Reduce each array element across the requested parallel dimensions.
4549 auto forOp = scf::ForOp::create(rewriter, loc, lb, ub, step);
4550 {
4551 OpBuilder::InsertionGuard guard(rewriter);
4552 rewriter.setInsertionPoint(forOp.getBody()->getTerminator());
4553 Value iv = forOp.getInductionVar();
4554 SmallVector<Value> indices{iv};
4555 if (memrefTy.getRank() > 1) {
4556 indices.resize(memrefTy.getRank());
4557 Value linearIndex = iv;
4558 for (int64_t dim = memrefTy.getRank() - 1; dim >= 0; --dim) {
4559 Value dimSize =
4560 memrefTy.isDynamicDim(dim)
4561 ? memref::DimOp::create(rewriter, loc, memref, dim).getResult()
4562 : arith::ConstantIndexOp::create(rewriter, loc,
4563 memrefTy.getDimSize(dim))
4564 .getResult();
4565 indices[dim] =
4566 arith::RemUIOp::create(rewriter, loc, linearIndex, dimSize);
4567 if (dim != 0)
4568 linearIndex =
4569 arith::DivUIOp::create(rewriter, loc, linearIndex, dimSize);
4570 }
4571 }
4572 Value elem = memref::LoadOp::create(rewriter, loc, memref, indices);
4573 createGPUAllReduceOp(loc, elem, memref, kind, op.getParDims(), indices,
4574 /*isPerThreadPrivateTarget=*/true);
4575 }
4576
4577 eraseDeadBounds();
4578}
4579
4580void ACCCGToGPULowering::processReductionOp(acc::ReductionInitOp op) {
4581 // Clone the inner ops of the reduction op only
4582 op.getRegion().walk<WalkOrder::PreOrder>([&](Operation *innerOp) {
4583 if (acc::YieldOp yieldOp = dyn_cast<acc::YieldOp>(innerOp)) {
4584 op.getResult().replaceAllUsesWith(mapping.lookup(yieldOp.getOperand(0)));
4585 return WalkResult::interrupt();
4586 }
4587 if (innerOp->getNumRegions() > 0) {
4588 processOp(innerOp);
4589 return WalkResult::skip();
4590 }
4591 rewriter.clone(*innerOp, mapping);
4592 return WalkResult::advance();
4593 });
4594}
4595
4596void ACCCGToGPULowering::processReductionCombineOp(acc::ReductionCombineOp op) {
4597 LLVM_DEBUG(llvm::dbgs() << "processing reduction combine op: ";
4598 op->print(llvm::dbgs()); llvm::dbgs() << "\n");
4599 Location loc = op.getLoc();
4600 MemRefType memrefType = dyn_cast<MemRefType>(op.getSrcMemref().getType());
4601 assert(memrefType && "expected memref type for reduction combine op");
4602 assert(memrefType.getRank() == 0 &&
4603 "expected scalar memref type for reduction combine op");
4604 Type elTy = memrefType.getElementType();
4605 FailureOr<arith::AtomicRMWKind> kindOr =
4606 getReductionKind(op.getReductionOperator(), elTy, loc);
4607 if (failed(kindOr))
4608 return;
4609 arith::AtomicRMWKind kind = *kindOr;
4610
4611 Value srcMemref = mapping.lookupOrDefault(op.getSrcMemref());
4612 Value destMemref = mapping.lookupOrDefault(op.getDestMemref());
4613
4614 // A block par_dim normally means the accumulator is shared across blocks and
4615 // must be updated atomically. But when the destination resolves to a
4616 // thread-private stack alloca (e.g. an inner-loop reduction combining one
4617 // private accumulator into another private accumulator for the same thread),
4618 // the update is not visible to other threads and must not be atomic. Treat
4619 // such destinations as a plain load/combine/store below.
4620 bool destIsPerThreadPrivate = isa_and_nonnull<memref::AllocaOp>(
4621 unwrapMemRefConversion(destMemref).getDefiningOp());
4622
4623 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
4625 // An atomic is needed exactly when more than one block can reach the
4626 // destination. A block dimension in the reduction's parallel dims implies
4627 // that; so does a thread-only reduction in a multi-block launch, where every
4628 // block combines its own partial into the same shared slot.
4629 bool destIsGridShared =
4630 !destIsPerThreadPrivate &&
4631 (llvm::any_of(parDims,
4632 [](mlir::acc::GPUParallelDimAttr parDim) {
4633 return parDim.isAnyBlock();
4634 }) ||
4635 computeRegion.launchesMultipleBlocks());
4636 if (destIsGridShared) {
4637 // The predication (tid.x == 0 when subgroup-aligned) is already handled
4638 // by the parent predicate_region processing.
4639 // Reloading a grid-shared slot races with other blocks; record it and
4640 // replace with the block-reduced register value in the fixup.
4641 auto srcLoad =
4642 memref::LoadOp::create(rewriter, loc, srcMemref, ValueRange{});
4643 pendingCombineReloads.push_back({srcMemref, srcLoad});
4644 constructAtomicAccumulation(loc, destMemref, /*indices=*/{}, srcLoad, kind);
4645 return;
4646 }
4647
4648 // Atomic construction is not needed; lower this operation to typical
4649 // reduction update operations. E.g. dest = dest <kind> src
4650 auto srcLoad = memref::LoadOp::create(rewriter, loc, srcMemref, ValueRange{});
4651 auto destLoad =
4652 memref::LoadOp::create(rewriter, loc, destMemref, ValueRange{});
4653 Value combine = generateReductionOp(rewriter, loc, srcLoad, destLoad, kind);
4654 memref::StoreOp::create(rewriter, loc, combine, destMemref, ValueRange{});
4655}
4656
4657void ACCCGToGPULowering::processCombineRegionOp(
4658 acc::ReductionCombineRegionOp op) {
4659 LLVM_DEBUG(llvm::dbgs() << "processing combine region op: ";
4660 op->print(llvm::dbgs()); llvm::dbgs() << "\n");
4661 // A block par_dim on a combine into a thread-private stack alloca is not a
4662 // real cross-block accumulation (the alloca is not shared across blocks), so
4663 // it must use a plain load/combine/store rather than an atomic update.
4664 bool destIsPerThreadPrivate = isa_and_nonnull<memref::AllocaOp>(
4665 unwrapMemRefConversion(mapping.lookupOrDefault(op.getDestVar()))
4666 .getDefiningOp());
4667 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
4669 for (auto parDim : parDims) {
4670 if (parDim.isAnyBlock() && !destIsPerThreadPrivate) {
4671 // Block reduction directly stores to the accumulator using atomic.
4672 // The predication (tid.x == 0 when subgroup-aligned) is already handled
4673 // by the parent predicate_region processing.
4674 for (Operation *user : op.getSrcVar().getUsers()) {
4675 if (acc::ReductionAccumulateOp accumulateOp =
4676 dyn_cast<acc::ReductionAccumulateOp>(user)) {
4677 Location loc = accumulateOp.getLoc();
4678 FailureOr<arith::AtomicRMWKind> kind =
4679 getReductionKind(accumulateOp.getReductionOperator(),
4680 accumulateOp.getValue().getType(), loc);
4681 if (failed(kind))
4682 return;
4683 Value srcMemref = mapping.lookupOrDefault(accumulateOp.getMemref());
4684 // Recorded and patched in the fixup to avoid the reload race.
4685 auto reductionLoad =
4686 memref::LoadOp::create(rewriter, loc, srcMemref, ValueRange{});
4687 pendingCombineReloads.push_back({srcMemref, reductionLoad});
4688 constructAtomicAccumulation(loc,
4689 mapping.lookupOrDefault(op.getDestVar()),
4690 /*indices=*/{}, reductionLoad, *kind);
4691 return;
4692 }
4693 }
4694 // For decomposed complex reductions, the AccumulateOp was replaced
4695 // with real/imag AccumulateOps. Load from the private memref which
4696 // holds the reconstructed complex value.
4697 Value privateMemref = mapping.lookupOrDefault(op.getSrcVar());
4698 MemRefType memrefTy = cast<MemRefType>(privateMemref.getType());
4699 if (isa<ComplexType>(memrefTy.getElementType())) {
4700 Location loc = op.getLoc();
4701 Value reductionResult =
4702 memref::LoadOp::create(rewriter, loc, privateMemref, ValueRange{});
4703 arith::AtomicRMWKind kind = arith::AtomicRMWKind::addf;
4704 op.getRegion().walk([&](Operation *innerOp) {
4705 if (isa<complex::MulOp>(innerOp))
4706 kind = arith::AtomicRMWKind::mulf;
4707 });
4708 constructAtomicAccumulation(loc,
4709 mapping.lookupOrDefault(op.getDestVar()),
4710 /*indices=*/{}, reductionResult, kind);
4711 return;
4712 }
4713 }
4714 }
4715 op.getRegion().walk<WalkOrder::PreOrder>([&](Operation *innerOp) {
4716 if (acc::YieldOp yieldOp = dyn_cast<acc::YieldOp>(innerOp))
4717 return WalkResult::interrupt();
4718 if (innerOp->getNumRegions() > 0) {
4719 processOp(innerOp);
4720 return WalkResult::skip();
4721 }
4722 rewriter.clone(*innerOp, mapping);
4723 return WalkResult::advance();
4724 });
4725}
4726
4727void ACCCGToGPULowering::processGenericOp(Operation *op) {
4728 // Operations with no regions or operations for which we know
4729 // no recursive processing is needed can be fully cloned.
4730 LLVM_DEBUG(llvm::dbgs() << "processing generic op, cloning: ";
4731 op->print(llvm::dbgs()); llvm::dbgs() << "\n");
4732 Operation *newOp = rewriter.clone(*op, mapping);
4733 // update mapping as cloning creates different result values
4734 mapping.map(op->getResults(), newOp->getResults());
4735}
4736
4737void ACCCGToGPULowering::processGenericOpWithRegions(Operation *op) {
4738 // Generic handling for operations with regions
4739 LLVM_DEBUG(llvm::dbgs() << "processing generic op with regions: ";
4740 op->print(llvm::dbgs()); llvm::dbgs() << "\n");
4741
4742 // Clone the operation structure without its regions
4743 Operation *newOp = rewriter.cloneWithoutRegions(*op, mapping);
4744
4745 // Process each region recursively
4746 for (auto [oldRegion, newRegion] :
4747 llvm::zip(op->getRegions(), newOp->getRegions())) {
4748 // Create blocks in the new region corresponding to old region blocks
4749 for (auto &oldBlock : oldRegion.getBlocks()) {
4750 TypeRange argTypes = oldBlock.getArgumentTypes();
4751 size_t numArgs = argTypes.size();
4752 // Create new block with same argument types
4753 Block *newBlock =
4754 rewriter.createBlock(&newRegion, newRegion.end(), argTypes,
4755 SmallVector<Location>(numArgs, op->getLoc()));
4756
4757 // Map block arguments
4758 mapping.map(oldBlock.getArguments(), newBlock->getArguments());
4759
4760 // Process each operation in the block
4761 for (auto &innerOp : oldBlock.getOperations()) {
4762 OpBuilder::InsertionGuard guard(rewriter);
4763 rewriter.setInsertionPointToEnd(newBlock);
4764 processOp(&innerOp);
4765 }
4766 }
4767 }
4768 rewriter.setInsertionPointAfter(newOp);
4769
4770 // Update mapping for results
4771 mapping.map(op->getResults(), newOp->getResults());
4772}
4773
4774// thread through par dim to verify redundant/0 execution modes
4775void ACCCGToGPULowering::processOp(Operation *op) {
4776 if (isDeferredBarrierFlushPoint(op))
4777 flushDeferredBarriersBefore(op);
4778 if (mlir::acc::hasParDimsAttr(op) && isa<scf::ParallelOp>(op)) {
4779 // parallel loops require special processing based on parallel dimension
4780 // this is mutually recursive with processOp
4781 scf::ParallelOp parallelOp = cast<scf::ParallelOp>(op);
4782 processParallelOp(parallelOp);
4783 } else if (scf::ForOp seqLoop = dyn_cast<scf::ForOp>(op)) {
4784 processSeqLoop(seqLoop);
4785 } else if (acc::PrivatizeOp privatize = dyn_cast<acc::PrivatizeOp>(op)) {
4786 processPrivatize(privatize);
4787 } else if (acc::PrivateLocalOp privateLocal =
4788 dyn_cast<acc::PrivateLocalOp>(op)) {
4789 processPrivateLocal(privateLocal);
4790 } else if (acc::PredicateRegionOp predicateRegionOp =
4791 dyn_cast<acc::PredicateRegionOp>(op)) {
4792 processPredicateRegion(predicateRegionOp);
4793 } else if (acc::ReductionAccumulateOp accumulateOp =
4794 dyn_cast<acc::ReductionAccumulateOp>(op)) {
4795 processAccumulateOp(accumulateOp);
4796 } else if (auto accumulateArrayOp =
4797 dyn_cast<acc::ReductionAccumulateArrayOp>(op)) {
4798 processAccumulateArrayOp(accumulateArrayOp);
4799 } else if (acc::ReductionInitOp reductionInitOp =
4800 dyn_cast<acc::ReductionInitOp>(op)) {
4801 processReductionOp(reductionInitOp);
4802 } else if (acc::ReductionCombineOp reductionCombineOp =
4803 dyn_cast<acc::ReductionCombineOp>(op)) {
4804 processReductionCombineOp(reductionCombineOp);
4805 } else if (auto combineRegionOp =
4806 dyn_cast<acc::ReductionCombineRegionOp>(op)) {
4807 processCombineRegionOp(combineRegionOp);
4808 } else if (acc::ReductionOp accReductionOp = dyn_cast<acc::ReductionOp>(op)) {
4809 mapping.map(accReductionOp->getResult(0), accReductionOp.getVarPtr());
4810 } else if (mapping.contains(op)) {
4811 // do nothing, operation in mapping signals it is already taken care of
4812 LLVM_DEBUG(llvm::dbgs() << "skipping mapped op: " << *op << "\n");
4813 } else if (isa<acc::YieldOp>(op)) {
4814 for (auto [operand, result] :
4815 llvm::zip(op->getOperands(), op->getParentOp()->getResults())) {
4816 result.replaceAllUsesWith(mapping.lookup(operand));
4817 }
4818 } else if (isa<scf::ExecuteRegionOp>(op)) {
4819 processExecuteRegion(cast<scf::ExecuteRegionOp>(op));
4820 } else if (op->getNumRegions() == 0 ||
4821 isa<acc::OpenACCDialect>(op->getDialect())) {
4822 processGenericOp(op);
4823 } else {
4824 processGenericOpWithRegions(op);
4825 }
4826}
4827
4828/// Fold `acc.par_width` to its launch operand or constant one.
4829class RemoveParWidth : public OpRewritePattern<acc::ParWidthOp> {
4830 using OpRewritePattern<acc::ParWidthOp>::OpRewritePattern;
4831 LogicalResult matchAndRewrite(acc::ParWidthOp op,
4832 PatternRewriter &rewriter) const override {
4833 if (Value launchArg = op.getLaunchArg()) {
4834 rewriter.replaceOp(op, launchArg);
4835 } else {
4836 Value one = arith::ConstantIndexOp::create(rewriter, op.getLoc(), 1);
4837 rewriter.replaceOp(op, one);
4838 }
4839 return success();
4840 }
4841};
4842
4843/// Rewrite pattern that lowers `acc.compute_region` via ACCCGToGPULowering.
4844class ACCComputeRegionToGPUPattern
4845 : public OpRewritePattern<acc::ComputeRegionOp> {
4846public:
4847 ACCComputeRegionToGPUPattern(MLIRContext *context,
4848 acc::OpenACCSupport &accSupport,
4849 const ACCCGToGPUOptions &options)
4850 : OpRewritePattern<acc::ComputeRegionOp>(context), accSupport(accSupport),
4851 options(options) {}
4852
4853 LogicalResult matchAndRewrite(acc::ComputeRegionOp op,
4854 PatternRewriter &rewriter) const override {
4855 ACCCGToGPULowering kernelOpRewriter(op, rewriter, accSupport, options);
4856 return kernelOpRewriter.rewrite();
4857 }
4858
4859private:
4860 acc::OpenACCSupport &accSupport;
4861 const ACCCGToGPUOptions &options;
4862};
4863
4864class ACCCGToGPU : public acc::impl::ACCCGToGPUBase<ACCCGToGPU> {
4865public:
4866 using acc::impl::ACCCGToGPUBase<ACCCGToGPU>::ACCCGToGPUBase;
4867
4868 void getDependentDialects(DialectRegistry &registry) const override {
4871 }
4872
4873 void runOnOperation() override {
4874 FunctionOpInterface funcOp = getOperation();
4875 MLIRContext *context = funcOp->getContext();
4876
4877 assert(deviceType != mlir::acc::DeviceType::Host &&
4878 deviceType != mlir::acc::DeviceType::Multicore &&
4879 "ACCCGToGPU only supports GPU device types");
4880
4881 // Validate parallel-loop mappings before any compute region is rewritten.
4882 // Loops outside compute regions do not require GPU mappings.
4883 WalkResult result = funcOp->walk([](scf::ParallelOp loop) {
4884 if (!loop->getParentOfType<acc::ComputeRegionOp>() ||
4886 return WalkResult::advance();
4887 loop.emitOpError("requires an 'acc.par_dims' attribute");
4888 return WalkResult::interrupt();
4889 });
4890 if (result.wasInterrupted()) {
4891 signalPassFailure();
4892 return;
4893 }
4894
4895 ACCCGToGPUOptions options;
4896 options.deviceType = deviceType;
4897 options.maxWorkgroupSharedMemory = maxWorkgroupSharedMemory;
4898 options.maxThreadPrivateStack = maxThreadPrivateStack;
4899 options.subgroupSize = subgroupSize;
4900
4901 // Try to get cached parent analysis first, fall back to local analysis.
4902 std::optional<std::reference_wrapper<acc::OpenACCSupport>> cachedAnalysis =
4903 getCachedParentAnalysis<acc::OpenACCSupport>(funcOp->getParentOp());
4904 acc::OpenACCSupport &accSupport = cachedAnalysis
4905 ? cachedAnalysis->get()
4906 : getAnalysis<acc::OpenACCSupport>();
4907
4908 RewritePatternSet patterns(context);
4909 patterns.insert<ACCComputeRegionToGPUPattern>(context, accSupport, options);
4910 patterns.insert<RemoveParWidth>(context);
4911 ConversionTarget target(getContext());
4912 target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
4913 target.addIllegalOp<acc::ComputeRegionOp, acc::ParWidthOp>();
4914 if (failed(applyPartialConversion(getOperation(), target,
4915 std::move(patterns)))) {
4916 signalPassFailure();
4917 }
4918 }
4919};
4920} // namespace
return success()
static void createForAllDimensions(OpBuilder &builder, Location loc, SmallVectorImpl< Value > &values)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
if(!isCopyOut)
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 copies
Creates a buffer in the faster memory space for the specified memref region (memref has to be non-zer...
auto load
@ None
static llvm::ManagedStatic< PassManagerOptions > options
static void rewrite(DataFlowSolver &solver, MLIRContext *context, MutableArrayRef< Region > initialRegions)
Rewrite the given regions using the computing analysis.
Definition SCCP.cpp:67
Block represents an ordered list of Operations.
Definition Block.h:34
MutableArrayRef< BlockArgument > BlockArgListType
Definition Block.h:110
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
RetT walk(FnT &&callback)
Walk all nested operations, blocks (including this block) or regions, depending on the type of callba...
Definition Block.h:318
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
Definition Block.cpp:255
BlockArgListType getArguments()
Definition Block.h:112
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
IntegerType getI32Type()
Definition Builders.cpp:71
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
IntegerType getI1Type()
Definition Builders.cpp:61
Location getUnknownLoc()
Definition Builders.cpp:25
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
IntegerType getI8Type()
Definition Builders.cpp:67
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:65
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
bool contains(T from) const
Checks to see if a mapping for 'from' exists.
Definition IRMapping.h:51
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:58
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
This class helps build Operations.
Definition Builders.h:210
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Definition Builders.h:448
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
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 setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition Builders.h:445
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 * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Definition Builders.h:596
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
Value getOperand(unsigned idx)
Definition Operation.h:377
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
unsigned getNumSuccessors()
Definition Operation.h:760
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
result_iterator result_begin()
Definition Operation.h:440
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
unsigned getNumOperands()
Definition Operation.h:373
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
void print(raw_ostream &os, const OpPrintingFlags &flags={})
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
result_iterator result_end()
Definition Operation.h:441
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
void setSuccessor(Block *block, unsigned index)
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition Operation.h:288
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
Block * getSuccessor(unsigned index)
Definition Operation.h:762
result_range getResults()
Definition Operation.h:442
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
Block & back()
Definition Region.h:64
iterator end()
Definition Region.h:56
iterator begin()
Definition Region.h:55
BlockListType & getBlocks()
Definition Region.h:45
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.
Resource * getResource() const
Return the resource that the effect applies to.
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
Definition SymbolTable.h:25
Operation * lookup(StringRef name) const
Look up a symbol with the specified name, returning null if no such name exists.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIndex() const
Definition Types.cpp:56
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
auto walk(WalkFns &&...walkFns)
Walk this type and all attibutes/types nested within using the provided walk functions.
Definition Types.h:220
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
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_iterator user_begin() const
Definition Value.h:216
user_range getUsers() const
Definition Value.h:218
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
ParDimAttrT seqDim(MLIRContext *ctx) const
virtual ParDimAttrT map(MLIRContext *ctx, ParLevel level) const =0
Map an OpenACC parallelism level to target dimension.
ParDimAttrT vectorDim(MLIRContext *ctx) const
ParDimAttrT workerDim(MLIRContext *ctx) const
ParDimAttrT gangDim(MLIRContext *ctx, ParLevel level) const
Convenience methods for specific parallelism levels.
remark::detail::InFlightRemark emitRemark(Operation *op, std::function< std::string()> messageFn, llvm::StringRef category="openacc")
Emit an OpenACC remark with lazy message generation.
std::string getVariableName(Value v, VariableNameConfig config={})
Get the variable name for a given value.
InFlightDiagnostic emitNYI(Location loc, const Twine &message)
Report a case that is not yet supported by the implementation.
std::optional< TypeSizeAndAlignment > getTypeSizeAndAlignment(Type ty, ModuleOp module)
Returns the size and ABI alignment in bytes for ty.
bool tryAllocate(int64_t bytes, int64_t alignment=kDefaultAlignmentBytes)
Reserve bytes, rounding the current offset up to alignment first.
void getDependentDialects(::mlir::DialectRegistry &registry) const override
Return the dialect that must be loaded in the context before this pass.
Specialization of arith.constant op that returns an integer of index type.
Definition Arith.h:85
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:436
Specialization of arith.constant op that returns an integer value.
Definition Arith.h:26
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:335
SideEffects::EffectInstance< Effect > EffectInstance
Value getGPUSize(gpu::Processor processor, gpu::LaunchOp launch, const llvm::DenseMap< gpu::Processor, Value > &dimensionOps)
Return the launch dimension for processor from launch, or from dimensionOps when launch is null.
ParLevel getGangParLevel(int64_t gangDimValue)
Convert a gang dimension value (1, 2, or 3) to the corresponding ParLevel.
GPUParallelDimsAttr getParDimsAttr(Operation *op)
Obtain the parallel dimensions carried by op, if any.
MemRefType getPrivateBaseMemRefType(Type baseTy, ModuleOp module)
Returns the ranked MemRef type used to allocate privatized storage.
SmallVector< GPUParallelDimAttr > getReductionCombineParDims(ReductionCombineOp op)
Returns the parallel dimensions that participate in op's combine step.
void insertParDim(llvm::SmallVector< GPUParallelDimAttr > &parDims, GPUParallelDimAttr parDim)
Insert parDim into parDims while preserving dimension ordering.
static constexpr StringLiteral getSpecializedRoutineAttrName()
Definition OpenACC.h:202
bool hasParDimsAttr(Operation *op)
Return whether op carries parallel dimensions.
std::optional< arith::AtomicRMWKind > translateACCReductionOperator(ReductionOperator redOp, Type type)
Maps an acc reduction operator to the arith atomic RMW kind for type.
bool isSpecializedAccRoutine(mlir::Operation *op)
Used to check whether this is a specialized accelerator version of acc routine function.
Definition OpenACC.h:214
static bool isInsideACCSpecializedRoutine(Operation *op)
Value createIdentityValue(OpBuilder &b, Location loc, Type type, arith::AtomicRMWKind kind, bool useOnlyFiniteValue=true)
Creates the identity (neutral) value for a reduction of type and kind.
FailureOr< bool > isPrivateLocalSharedMemoryCandidate(PrivateLocalOp privateLocal, ComputeRegionOp computeRegion, ModuleOp module, const ACCToGPUMappingPolicy &policy, OpenACCSupport *support=nullptr)
True when privateLocal may be placed in shared memory.
static constexpr StringLiteral getRoutineInfoAttrName()
Definition OpenACC.h:198
Value castPointerLikeTypeIfNeeded(OpBuilder &builder, Location loc, Value value, Type resultType)
Cast value to resultType via PointerLikeType::genCast when needed.
int64_t sumExistingSharedMemoryBytes(Region &region)
Sum aligned static_upper_bound_bytes for all acc.gpu_shared_memory in region.
Value getGPUThreadId(gpu::Processor processor, gpu::LaunchOp launch, const llvm::DenseMap< gpu::Processor, Value > &indexOps)
Return the thread/block index for processor from launch, or from indexOps when launch is null.
PrivatizeOp getPrivatizeOp(PrivateLocalOp privateLocal, ComputeRegionOp computeRegion)
Resolve the acc.privatize operation associated with a private local.
void registerAllExtensions(DialectRegistry &registry)
Register the standard OpenACC models for GPU, LLVM and MemRef IR.
bool hasGPUBlockRedundantAttr(Operation *op)
Return whether op is marked with the acc.gpu_block_redundant attribute, i.e.
Value generateReductionOp(OpBuilder &b, Location loc, Value lhs, Value rhs, arith::AtomicRMWKind kind)
Combines two reduction partial values using the operator for kind.
void removeParDim(llvm::SmallVector< GPUParallelDimAttr > &parDims, GPUParallelDimAttr parDim)
Remove parDim from parDims if present.
void setParDimsAttr(Operation *op, GPUParallelDimsAttr attr)
Set parallel dimensions on op.
ActiveParDimsAttr getActiveParDimsAttr(Operation *op)
Obtain the active parallel dimensions carried by op, if any.
std::optional< int64_t > getPrivateLocalSharedMemoryUpperBoundBytes(PrivateLocalOp privateLocal, ComputeRegionOp computeRegion, ModuleOp module, const ACCToGPUMappingPolicy &policy, OpenACCSupport *support=nullptr)
Upper-bound byte size for a shared-memory private_local candidate, or std::nullopt when not eligible ...
static bool isThreadXPrivatize(PrivatizeOp privatize)
ACCParMappingPolicy< mlir::acc::GPUParallelDimAttr > ACCToGPUMappingPolicy
Type alias for the GPU-specific mapping policy.
InFlightDiagnostic & next(InFlightDiagnostic &diag)
Starts a new message part in an in-flight diagnostic.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
LoopNest buildLoopNest(OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs, ValueRange steps, ValueRange iterArgs, function_ref< ValueVector(OpBuilder &, Location, ValueRange, ValueRange)> bodyBuilder=nullptr)
Creates a perfect nest of "for" loops, i.e.
Definition SCF.cpp:821
Value constantOne(OpBuilder &builder, Location loc, Type tp)
Generates a 1-valued constant of the given type.
OwningOpRef< spirv::ModuleOp > combine(ArrayRef< spirv::ModuleOp > inputModules, OpBuilder &combinedModuleBuilder, SymbolRenameListener symRenameListener)
Combines a list of SPIR-V inputModules into one.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
Definition Matchers.h:527
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
Value getValueOrCreateCastToIndexLike(OpBuilder &b, Location loc, Type targetType, Value value)
Create a cast from an index-like value (index or integer) to another index-like value.
Definition Utils.cpp:122
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369