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"
137#define GEN_PASS_DEF_ACCCGTOGPU
138#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
142#define DEBUG_TYPE "acc-cg-to-gpu"
148enum class PrivateMemScope { Thread, Worker, Gang,
None };
151static std::string getDeviceRemarkQualifier(DeviceType deviceType) {
152 switch (deviceType) {
153 case DeviceType::None:
154 case DeviceType::Star:
155 case DeviceType::Default:
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";
170 FunctionOpInterface funcOp = op->
getParentOfType<FunctionOpInterface>();
175static GPUParallelDimAttr
176getAccRoutineParDim(RoutineOp routineOp,
MLIRContext *ctx,
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();
184 return policy.
gangDim(ctx, gangLevel);
186 if (routineOp.hasGang() || routineOp.hasGang(DeviceType::Nvidia))
187 return policy.
gangDim(ctx, ParLevel::gang_dim1);
188 if (routineOp.hasWorker() || routineOp.hasWorker(DeviceType::Nvidia))
190 if (routineOp.hasVector() || routineOp.hasVector(DeviceType::Nvidia))
192 return policy.
seqDim(ctx);
196static RoutineOp getRoutineOpForAccRoutineFunction(FunctionOpInterface funcOp,
199 SpecializedRoutineAttr attr =
200 funcOp->getDiscardableAttrOfType<SpecializedRoutineAttr>(
202 return symTab.
lookup<RoutineOp>(attr.getRoutine().getLeafReference());
204 RoutineInfoAttr routineInfo =
205 funcOp->getDiscardableAttrOfType<RoutineInfoAttr>(
207 if (!routineInfo || routineInfo.getAccRoutines().empty())
209 return symTab.
lookup<RoutineOp>(
210 routineInfo.getAccRoutines().front().getLeafReference());
214static GPUParallelDimAttr
215getSpecializedRoutineDim(FunctionOpInterface funcOp,
217 SpecializedRoutineAttr specAttr =
218 funcOp->getDiscardableAttrOfType<SpecializedRoutineAttr>(
220 assert(specAttr &&
"expected specialized routine attribute");
221 return policy.
map(funcOp->getContext(), specAttr.getLevel().getValue());
225static GPUParallelDimAttr
226getAccRoutineCallParDim(CallOpInterface callOp,
228 std::optional<CallInterfaceCallable> callee = callOp.getCallableForCallee();
231 SymbolRefAttr calleeSymbolRef = dyn_cast<SymbolRefAttr>(*callee);
232 if (!calleeSymbolRef)
234 ModuleOp moduleOp = callOp->getParentOfType<ModuleOp>();
239 FunctionOpInterface funcOp =
240 symTab.
lookup<FunctionOpInterface>(calleeSymbolRef.getLeafReference());
245 return getSpecializedRoutineDim(funcOp, policy);
246 if (RoutineOp routineOp = getRoutineOpForAccRoutineFunction(funcOp, symTab))
247 return getAccRoutineParDim(routineOp, funcOp.getContext(), policy);
254 ComputeRegionOp computeRegion = op->
getParentOfType<ComputeRegionOp>();
255 assert(computeRegion &&
"missing enclosing acc.compute_region");
258 bool isInnermostParallelParent =
true;
260 bool hasNonSeqParDim =
false;
261 if (GPUParallelDimsAttr parDimsAttr =
getParDimsAttr(parentLoop)) {
262 for (GPUParallelDimAttr parDim : parDimsAttr.getArray()) {
265 hasNonSeqParDim =
true;
276 (hasNonSeqParDim || isInnermostParallelParent))
277 for (GPUParallelDimAttr parDim : computeRegion.getLaunchParDims())
279 isInnermostParallelParent =
false;
280 parentLoop = parentLoop->getParentOfType<scf::ParallelOp>();
283 if (GPUParallelDimsAttr parDimsAttr =
getParDimsAttr(computeRegion))
284 for (GPUParallelDimAttr parDim : parDimsAttr.getArray())
290static Value stripIndexCastsFromValue(
Value x) {
294 while (arith::IndexCastOp castOp = dyn_cast<arith::IndexCastOp>(op)) {
303static FailureOr<int64_t> extractIntConst(
Value x,
304 bool stripIndexCasts =
false) {
306 x = stripIndexCastsFromValue(x);
310 assert(constOp.getType().getIntOrFloatBitWidth() <= 64);
311 return constOp.value();
314 return constOp.value();
321 x = stripIndexCastsFromValue(x);
322 FailureOr<int64_t> conX = extractIntConst(x);
329static bool getPassThroughResults(
Operation *userOp,
Value trackedOperand,
331 if (ViewLikeOpInterface viewLikeOp = dyn_cast<ViewLikeOpInterface>(userOp)) {
332 if (viewLikeOp.getViewSource() == trackedOperand) {
333 passThroughResults.push_back(viewLikeOp.getViewDest());
342 if (acc::PartialEntityAccessOpInterface partialAccess =
343 dyn_cast<acc::PartialEntityAccessOpInterface>(userOp)) {
344 if (partialAccess.getBaseEntity() == trackedOperand) {
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();
374static void getStorageSourceOperands(
Operation *def,
376 if (ViewLikeOpInterface viewLike = dyn_cast<ViewLikeOpInterface>(def)) {
377 sources.push_back(viewLike.getViewSource());
380 if (acc::PartialEntityAccessOpInterface partialAccess =
381 dyn_cast<acc::PartialEntityAccessOpInterface>(def)) {
382 if (
Value base = partialAccess.getBaseEntity())
383 sources.push_back(base);
387 if (!isa<IntegerType, IndexType, FloatType, ComplexType>(operand.getType()))
388 sources.push_back(operand);
393static acc::PrivateLocalOp getPrivateLocalForMemref(
Value memref);
396static GPUParallelDimsAttr
397getPrivateParDims(acc::PrivateLocalOp privateLocal,
398 acc::ComputeRegionOp computeRegion);
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();
419 if (GPUParallelDimsAttr parDimsAttr = privatize.getParDimsAttr())
420 return llvm::any_of(parDimsAttr.getArray(),
421 [](GPUParallelDimAttr d) { return d.isThreadX(); });
427static bool isInsideConditional(
Block *block) {
431 parent && !isa<gpu::LaunchOp, FunctionOpInterface>(parent);
433 if (isa<RegionBranchOpInterface>(parent) &&
434 !isa<LoopLikeOpInterface, scf::ExecuteRegionOp>(parent))
441 gpu::BarrierOp::create(builder, loc);
446 gpu::BarrierOp::create(builder, loc,
ArrayAttr{},
448 gpu::BarrierScope::Subgroup);
456 assert(rowWidth > 0 && subgroupSize % rowWidth == 0 &&
457 "row must tile the subgroup");
459 int64_t rowsPerSubgroup = subgroupSize / rowWidth;
465 Value threadY32 = arith::IndexCastOp::create(builder, loc, i32Ty, threadY);
468 Value rowIndex = arith::AndIOp::create(builder, loc, threadY32, rowMask);
470 Value laneBase = arith::MulIOp::create(builder, loc, rowIndex, width);
474 Value mask = arith::ShLIOp::create(builder, loc, laneBits, laneBase);
475 NVVM::SyncWarpOp::create(builder, loc, mask);
481struct SharedStorage {
482 llvm::SmallPtrSet<Value, 8> roots;
483 bool unknown =
false;
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;
493class ACCCGToGPULowering {
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),
502 options.maxWorkgroupSharedMemory,
508 gpu::LaunchOp getLaunch()
const {
return launch; }
510 bool hasFailed =
false;
511 bool insideAccumulateGridStride =
false;
512 Value reductionSharedBuf;
515 llvm::DenseMap<Value, Value> reductionAccumValue;
517 llvm::SmallVector<std::pair<Value, memref::LoadOp>> pendingCombineReloads;
521 void processParallelOp(scf::ParallelOp parallelOp);
523 template <
typename LoopOp>
524 void processSeqLoop(LoopOp loopOp);
526 void processPredicateRegion(acc::PredicateRegionOp interOp);
529 processPrivateLocal(acc::PrivateLocalOp privateLocal,
530 std::optional<int64_t> sharedMemCopies = std::nullopt);
532 Value processPrivatize(acc::PrivatizeOp privatize);
534 Value allocatePrivatizeHeapStorage(acc::PrivatizeOp privatize,
538 void processExecuteRegion(scf::ExecuteRegionOp op);
540 void processAccumulateOp(acc::ReductionAccumulateOp op);
542 void processAccumulateArrayOp(acc::ReductionAccumulateArrayOp op);
544 void processReductionOp(acc::ReductionInitOp op);
546 void processReductionCombineOp(acc::ReductionCombineOp op);
548 void processCombineRegionOp(acc::ReductionCombineRegionOp op);
550 void processGenericOp(Operation *op);
552 void processGenericOpWithRegions(Operation *op);
554 void processOp(Operation *op);
557 void constructAtomicAccumulation(Location loc, Value memref,
559 arith::AtomicRMWKind kind);
562 FailureOr<arith::AtomicRMWKind> getReductionKind(acc::ReductionOperator redOp,
563 Type type, Location loc);
567 std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
568 SmallVector<mlir::acc::GPUParallelDimAttr>>
569 computeActiveAndInactiveParDims(Operation *op,
Block *block);
573 emitPredicate(Location loc,
574 SmallVector<mlir::acc::GPUParallelDimAttr> &inactiveParDims);
578 std::optional<int64_t>
579 isEligibleForSharedMemory(acc::PrivateLocalOp privateLocal,
583 bool tryAllocateSharedMemory(int64_t bytes);
589 void recordThreadPrivate(acc::PrivateLocalOp privateLocal);
592 void recordGlobalMemory(acc::PrivatizeOp privatizeOp);
595 int64_t getElementSizeInBytes(Location loc, Type elementType)
const;
598 bool canUseStackAlloca(MemRefType baseTy, Location loc,
599 int64_t maxThreadPrivateStack)
const;
602 void createBarrier(Location loc, mlir::acc::GPUParallelDimsAttr parDimsAttr);
608 void createPerRowBarrier(Location loc);
612 void createBarrierAfterSeqLoop(Operation *loopOp);
615 void flushDeferredBarriersBefore(Operation *beforeOp);
618 bool mayWriteSharedMemory(Operation *loopOp);
627 bool needsBarrierAfterThreadLoop(scf::ParallelOp loop);
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);
645 PrivateMemScope getPrivateMemScope(acc::PrivatizeOp privatizeOp);
648 PrivateMemScope getPrivateScopeForMemref(Value memref);
651 acc::PrivatizeOp getPrivatizeForMemref(Value memref);
657 void collectSharedPrivateStores(
658 Operation *root, llvm::SmallPtrSetImpl<Operation *> &gangPrivatizes,
659 llvm::SmallPtrSetImpl<Operation *> &workerPrivatizes);
663 bool isMatchingPrivateMemref(
664 Value memref, PrivateMemScope storeScope,
665 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes);
669 bool hasParallelPrivateReuse(
670 LoopLikeOpInterface seqLoopOp, Operation *skipOp,
671 PrivateMemScope storeScope,
672 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes);
676 PrivateMemScope needsPreStoreReuseBarrier(acc::PredicateRegionOp interOp);
680 bool needsInLoopReuseBarrier(Operation *loopOp);
683 void createGPUAllReduceOp(Location loc, Value input, Value memref,
684 arith::AtomicRMWKind kind,
685 mlir::acc::GPUParallelDimsAttr parDimsAttr,
687 bool isPerThreadPrivateTarget =
false);
690 void postprocessAccumulateOp(acc::ReductionAccumulateOp op);
693 void postprocessLoopReduction(scf::ParallelOp parLoop);
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);
729 BlockArgument getOrAppendInsBlockArg(Value outside) {
730 if (std::optional<BlockArgument> blockArg =
731 computeRegion.getBlockArg(outside)) {
734 return computeRegion.appendInputArg(outside);
738 void preparePrivatizeExtentInsOperands() {
739 computeRegion.walk([&](acc::PrivateLocalOp privateLocal) {
740 acc::PrivatizeOp privatizeOp =
742 if (privatizeOp->getParentOfType<acc::ComputeRegionOp>() == computeRegion)
744 for (Value extent : privatizeOp.getDynamicSizes())
745 getOrAppendInsBlockArg(extent);
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));
760 extents.push_back(mapping.lookupOrDefault(extent));
765 RewriterBase &rewriter;
766 acc::ComputeRegionOp computeRegion;
768 acc::OpenACCSupport &accSupport;
769 const ACCCGToGPUOptions &options;
770 gpu::LaunchOp launch;
772 llvm::SmallVector<scf::ParallelOp> loopReductions;
773 llvm::DenseMap<gpu::Processor, Value> threadIdMap;
774 llvm::DenseMap<gpu::Processor, Value> dimensionMap;
776 bool hasThreadYReduction =
false;
778 bool hasThreadXReduction =
false;
780 bool hasThreadLevelArrayReduction =
false;
783 llvm::DenseMap<Operation *, acc::ReductionAccumulateArrayOp>
784 threadArrayAccumulators;
786 bool hasThreadLevelRoutineCall =
false;
788 bool hasThreadYBarrier =
false;
791 llvm::DenseMap<Type, Value> privatizeBroadcastCache;
793 int64_t staticBlockDimX = 1024;
794 int64_t staticBlockDimY = 1024;
795 int64_t staticBlockDimZ = 1024;
800 bool isSingleThreadWorkerLaunch()
const {
801 return staticBlockDimX == 1 && staticBlockDimZ == 1 &&
802 staticBlockDimY > 1 && staticBlockDimY <= options.subgroupSize;
809 bool isWorkerOnlyShuffleLaunch()
const {
810 return hasThreadYReduction && !hasThreadXReduction &&
811 !hasThreadLevelArrayReduction && staticBlockDimZ == 1 &&
812 staticBlockDimY > 1 && staticBlockDimY <= options.subgroupSize &&
813 options.subgroupSize % staticBlockDimX == 0;
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;
823 Value getThreadId(Location loc, gpu::Dimension dim) {
824 return gpu::ThreadIdOp::create(rewriter, loc, rewriter.getIndexType(), dim);
827 Value getBlockDim(Location loc, gpu::Dimension dim) {
828 return gpu::BlockDimOp::create(rewriter, loc, rewriter.getIndexType(), dim);
832 Value getGPUThreadIdFor(gpu::Processor proc) {
837 Value getGPUSizeFor(gpu::Processor proc) {
838 return getGPUSize(proc, getLaunch(), dimensionMap);
843 Type elementType)
const {
844 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
845 if (std::optional<acc::TypeSizeAndAlignment> sizeAndAlignment =
847 return sizeAndAlignment->first.getFixedValue();
850 llvm::raw_string_ostream os(msg);
851 os <<
"element size computation for unsupported type: " << elementType;
852 (void)accSupport.
emitNYI(loc, os.str());
856bool ACCCGToGPULowering::canUseStackAlloca(
857 MemRefType baseTy, Location loc, int64_t maxThreadPrivateStack)
const {
858 for (int64_t dim : baseTy.getShape())
859 if (dim == ShapedType::kDynamic)
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))
868 return elementSize * numElements < maxThreadPrivateStack;
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(); });
881 if (hasBlock(accArr.getParDimsAttr()))
883 for (scf::ParallelOp loop = accArr->getParentOfType<scf::ParallelOp>(); loop;
884 loop = loop->getParentOfType<scf::ParallelOp>()) {
894static acc::ReductionAccumulateArrayOp perThreadArrayReductionAccum(Value v) {
895 SmallVector<Value> worklist{v};
897 while (!worklist.empty()) {
898 Value cur = worklist.pop_back_val();
899 if (!seen.insert(cur).second)
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))
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());
924static void initPerThreadArrayAccum(OpBuilder &
b, Location loc, Value alloca,
926 arith::AtomicRMWKind kind) {
927 assert(baseTy.getRank() > 0 && baseTy.hasStaticShape() &&
928 "per-thread array reduction accumulator must be static ranked");
934 auto buildLoopNest = [&](
auto &&self,
unsigned dim) ->
void {
935 if (dim == baseTy.getRank()) {
936 memref::StoreOp::create(
b, loc, ident, alloca,
indices);
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());
958isArrayReductionPartialUpdate(Operation *writer,
959 acc::ReductionAccumulateArrayOp accArr) {
960 memref::StoreOp store = dyn_cast<memref::StoreOp>(writer);
963 Value value = store.getValueToStore();
967 std::optional<arith::AtomicRMWKind> kind =
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},
976 if (isFloatKind != isa<FloatType>(type))
982 for (
bool useOnlyFiniteValue : {
true,
false}) {
983 TypedAttr ident = arith::getIdentityValueAttr(
984 *kind, type,
b, writer->
getLoc(), useOnlyFiniteValue);
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)
997std::optional<int64_t>
998ACCCGToGPULowering::isEligibleForSharedMemory(acc::PrivateLocalOp privateLocal,
1003 if (perThreadArrayReductionAccum(privateLocal.getResult()) &&
1004 storageHasThreadX(privateLocal, computeRegion))
1005 return std::nullopt;
1006 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
1008 privateLocal, computeRegion, module, defaultPolicy, &accSupport);
1009 if (
failed(isCandidate)) {
1011 return std::nullopt;
1013 if (!isCandidate.value())
1014 return std::nullopt;
1015 std::optional<int64_t> upperBound =
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())
1024 return *upperBound / (elementSize * numElements);
1027bool ACCCGToGPULowering::tryAllocateSharedMemory(int64_t bytes) {
1031void ACCCGToGPULowering::recordThreadPrivate(acc::PrivateLocalOp privateLocal) {
1032 std::string varName = accSupport.
getVariableName(privateLocal.getResult());
1034 if (varName.empty())
1037 if (!llvm::is_contained(threadPrivateVarNames, varName))
1038 threadPrivateVarNames.push_back(varName);
1041void ACCCGToGPULowering::recordGlobalMemory(acc::PrivatizeOp privatizeOp) {
1042 std::string varName = accSupport.
getVariableName(privatizeOp.getResult());
1044 if (varName.empty())
1047 if (!llvm::is_contained(globalMemVarNames, varName))
1048 globalMemVarNames.push_back(varName);
1051FailureOr<arith::AtomicRMWKind>
1052ACCCGToGPULowering::getReductionKind(acc::ReductionOperator redOp, Type type,
1054 if (std::optional<arith::AtomicRMWKind> kind =
1059 llvm::raw_string_ostream os(msg);
1060 os <<
"reduction operator (" << redOp <<
") for type " << type;
1061 (void)accSupport.
emitNYI(loc, os.str());
1065LogicalResult ACCCGToGPULowering::rewrite() {
1071 computeRegion->walk([&](acc::ReductionAccumulateOp op) {
1072 for (
auto parDim : op.getParDimsAttr().getArray()) {
1073 hasThreadXReduction |= parDim.isThreadX();
1074 hasThreadYReduction |= parDim.isThreadY();
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();
1085 if (acc::PrivateLocalOp privateLocal =
1086 getPrivateLocalForMemref(op.getMemref()))
1087 threadArrayAccumulators.try_emplace(privateLocal, op);
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;
1105 Location loc = computeRegion->getLoc();
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
1116 << maybeLaunchArg.value_or(constantOne) <<
"\n");
1120 maybeLaunchArg.value_or(constantOne));
1122 LLVM_DEBUG(llvm::dbgs() <<
"ACCCGToGPU: creating gpu launch op: \n");
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);
1131 mapping.
map(computeRegion.gpuParWidth(processor), launchArg);
1134 llvm::StringRef blockDimXName =
"blockDim.x";
1135 llvm::StringRef blockDimYName =
"blockDim.y";
1136 std::string deviceLabel = getDeviceRemarkQualifier(
options.deviceType);
1138 if (!computeRegion->getParentOfType<gpu::GPUFuncOp>()) {
1139 Value blockDimX = launchArgument(gpu::Processor::ThreadX);
1142 staticBlockDimX = bdxVal.getSExtValue();
1143 Value blockDimY = launchArgument(gpu::Processor::ThreadY);
1146 staticBlockDimY = bdyVal.getSExtValue();
1147 Value blockDimZ = launchArgument(gpu::Processor::ThreadZ);
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);
1159 auto getName = [&](Value val) -> std::string {
1162 width && *width < 0)
1165 return name.empty() ?
"(*)" : name;
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))
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,
1193 launch.getAsyncDependenciesMutable().append(streamValue);
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);
1203 if (
auto kernelFuncName = computeRegion.getKernelFuncNameAttr())
1204 launch.setFunctionAttr(kernelFuncName);
1205 if (
auto kernelModuleName = computeRegion.getKernelModuleNameAttr())
1206 launch.setModuleAttr(kernelModuleName);
1209 gpu::TerminatorOp::create(rewriter, loc);
1211 mapLaunchArguments(gpu::Processor::BlockX,
1212 gpu::GridDimOp::create(rewriter, loc,
1214 gpu::Dimension::x));
1215 mapLaunchArguments(gpu::Processor::BlockY,
1216 gpu::GridDimOp::create(rewriter, loc,
1218 gpu::Dimension::y));
1219 mapLaunchArguments(gpu::Processor::BlockZ,
1220 gpu::GridDimOp::create(rewriter, loc,
1222 gpu::Dimension::z));
1223 mapLaunchArguments(gpu::Processor::ThreadX,
1224 gpu::BlockDimOp::create(rewriter, loc,
1226 gpu::Dimension::x));
1227 mapLaunchArguments(gpu::Processor::ThreadY,
1228 gpu::BlockDimOp::create(rewriter, loc,
1230 gpu::Dimension::y));
1231 mapLaunchArguments(gpu::Processor::ThreadZ,
1232 gpu::BlockDimOp::create(rewriter, loc,
1234 gpu::Dimension::z));
1239 OpBuilder::InsertionGuard guard(rewriter);
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]);
1258 preparePrivatizeExtentInsOperands();
1259 Block *body = computeRegion.getBody();
1260 unsigned numLaunchArgs = computeRegion.getLaunchArgs().size();
1261 ValueRange inputArgs = computeRegion.getInputArgs();
1265 assert(computeRegion.getRegion().hasOneBlock() &&
1266 "compute region only supports one block region for now");
1268 for (
auto &op : computeRegion.getRegion().getBlocks().front().getOperations())
1271 for (
auto &parLoop : loopReductions)
1272 postprocessLoopReduction(parLoop);
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())
1283 if (!domInfo.dominates(it->second, loadOp.getOperation()))
1290 const int64_t subgroupSize =
options.subgroupSize;
1291 const int64_t subgroupAlignMask = subgroupSize - 1;
1299 bool needsThreadXAlign =
false;
1300 bool needsThreadYAlign =
false;
1301 bool alignThreadXReduction =
1307 auto classifyAllReduce = [&](gpu::AllReduceOp allReduce) {
1308 bool hasThreadX =
false;
1309 bool hasThreadY =
false;
1311 hasThreadX |= parDim.isThreadX();
1312 hasThreadY |= parDim.isThreadY();
1314 if (hasThreadX && alignThreadXReduction)
1315 needsThreadXAlign =
true;
1316 else if (hasThreadY)
1317 needsThreadYAlign =
true;
1320 launch.walk(classifyAllReduce);
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);
1329 bool isShuffleEnabled = needsThreadXAlign || needsThreadYAlign;
1331 std::optional<int64_t> constBlockDimX =
1333 std::optional<int64_t> constBlockDimY =
1335 std::optional<int64_t> constBlockDimZ =
1343 bool skipAlign = constBlockDimX && constBlockDimY && constBlockDimZ &&
1344 *constBlockDimX > 1 && *constBlockDimX < subgroupSize &&
1345 *constBlockDimY == 1 && *constBlockDimZ == 1;
1350 if (isSingleThreadWorkerLaunch())
1352 if (needsThreadYAlign && !needsThreadXAlign && !hasThreadYBarrier &&
1353 isWorkerOnlyShuffleLaunch())
1356 if ((isShuffleEnabled || hasThreadYBarrier) && !skipAlign) {
1359 Value curBlockDimX = launch.getBlockSizeX();
1360 Value curBlockDimY = launch.getBlockSizeY();
1361 Value curBlockDimZ = launch.getBlockSizeZ();
1365 auto getName = [&](Value val) -> std::string {
1367 return name.empty() ?
"(*)" : name;
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 "
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 +
")`")
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);
1402 std::max<int64_t>(1, numThreads / (alignedBdx * newBdy));
1409 Value numXYThreads =
1410 arith::MulIOp::create(rewriter, loc, curBlockDimX, curBlockDimY);
1412 arith::MulIOp::create(rewriter, loc, numXYThreads, curBlockDimZ);
1416 Value cstSubgroupSize =
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,
1426 arith::DivUIOp::create(rewriter, loc, numXYThreads, newBlockDimX);
1428 newBlockDimY = arith::MaxUIOp::create(rewriter, loc, cst1, quotient);
1430 Value newNumXYThreads =
1431 arith::MulIOp::create(rewriter, loc, newBlockDimX, newBlockDimY);
1433 arith::DivUIOp::create(rewriter, loc, numThreads, newNumXYThreads);
1434 newBlockDimZ = arith::MaxUIOp::create(rewriter, loc, cst1, quotient);
1437 launch.getBlockSizeXMutable().assign(newBlockDimX);
1438 launch.getBlockSizeYMutable().assign(newBlockDimY);
1439 launch.getBlockSizeZMutable().assign(newBlockDimZ);
1446 if (!threadPrivateVarNames.empty()) {
1448 return (llvm::Twine(
"Local memory or registers used for ") +
1449 llvm::join(threadPrivateVarNames,
","))
1454 if (!sharedMemPrivateVarNames.empty()) {
1456 return (llvm::Twine(
"GPU shared memory used for ") +
1457 llvm::join(sharedMemPrivateVarNames,
","))
1462 if (!globalMemVarNames.empty()) {
1464 return (llvm::Twine(
"GPU global memory used for ") +
1465 llvm::join(globalMemVarNames,
","))
1470 rewriter.
eraseOp(computeRegion);
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)
1491 for (Operation *user : memref.
getUsers()) {
1492 acc::ReductionCombineOp combineOp = dyn_cast<acc::ReductionCombineOp>(user);
1493 if (!combineOp || combineOp.getDestMemref() != memref)
1495 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
1497 if (llvm::any_of(parDims, [](mlir::acc::GPUParallelDimAttr d) {
1498 return d.isAnyBlock();
1506static GPUParallelDimsAttr
1507getPrivateParDims(acc::PrivateLocalOp privateLocal,
1508 acc::ComputeRegionOp computeRegion) {
1511 if (acc::PrivatizeOp privatize =
getPrivatizeOp(privateLocal, computeRegion))
1512 return privatize.getParDimsAttr();
1517static bool isThreadYPrivate(acc::PrivateLocalOp privateLocal,
bool allowBlock,
1518 acc::ComputeRegionOp computeRegion) {
1521 GPUParallelDimsAttr parDims = getPrivateParDims(privateLocal, computeRegion);
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());
1531struct ThreadYBroadeningInfo {
1532 bool hasActiveWorkerCombine =
false;
1533 bool hasExplicitInactiveCombine =
false;
1534 bool hasBroadeningConflict =
false;
1535 Operation *diagnosticOp =
nullptr;
1537 void merge(
const ThreadYBroadeningInfo &other) {
1538 hasActiveWorkerCombine |= other.hasActiveWorkerCombine;
1539 hasExplicitInactiveCombine |= other.hasExplicitInactiveCombine;
1540 hasBroadeningConflict |= other.hasBroadeningConflict;
1542 diagnosticOp = other.diagnosticOp;
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());
1555 return !op->
hasTrait<OpTrait::HasRecursiveMemoryEffects>();
1560static bool isFedByInnerBlockCombine(acc::PrivateLocalOp accumulator,
1561 Operation *selfCombine) {
1564 for (Operation *user : accumulator.getResult().getUsers()) {
1565 if (user == selfCombine)
1567 auto combineOp = dyn_cast<acc::ReductionCombineOp>(user);
1569 unwrapMemRefConversion(combineOp.getDestMemref()).getDefiningOp() !=
1570 accumulator.getOperation())
1572 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
1574 if (llvm::any_of(parDims, [](mlir::acc::GPUParallelDimAttr d) {
1575 return d.isAnyBlock();
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 &&
1599 if (hasThreadY && hasBlock &&
1600 isThreadYPrivate(srcPrivate, hasPrivateDest, computeRegion)) {
1601 info.hasActiveWorkerCombine =
true;
1608 if (hasThreadY && hasBlock &&
1609 isThreadYPrivate(srcPrivate,
true, computeRegion) &&
1610 isFedByInnerBlockCombine(srcPrivate, combineOp)) {
1611 info.hasActiveWorkerCombine =
true;
1615 info.hasExplicitInactiveCombine =
true;
1616 if (!info.diagnosticOp)
1617 info.diagnosticOp = combineOp;
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;
1635 if (acc::ReductionCombineOp combineOp =
1636 dyn_cast<acc::ReductionCombineOp>(nestedOp)) {
1637 classifyThreadYCombine(
1638 info, combineOp, combineOp.getSrcMemref(), combineOp.getDestMemref(),
1642 if (acc::ReductionCombineRegionOp combineRegionOp =
1643 dyn_cast<acc::ReductionCombineRegionOp>(nestedOp)) {
1644 classifyThreadYCombine(info, combineRegionOp, combineRegionOp.getSrcVar(),
1645 combineRegionOp.getDestVar(),
1650 if (nestedOp.getNumRegions() != 0) {
1651 if (hasUnsafeEffectsWhenBroadening(&nestedOp)) {
1652 info.hasBroadeningConflict =
true;
1653 if (!info.diagnosticOp)
1654 info.diagnosticOp = &nestedOp;
1656 for (Region ®ion : nestedOp.getRegions())
1657 for (
Block &nestedBlock : region)
1658 info.merge(analyzeThreadYBroadening(nestedBlock, computeRegion));
1661 if (hasUnsafeEffectsWhenBroadening(&nestedOp)) {
1662 info.hasBroadeningConflict =
true;
1663 if (!info.diagnosticOp)
1664 info.diagnosticOp = &nestedOp;
1670std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
1671 SmallVector<mlir::acc::GPUParallelDimAttr>>
1672ACCCGToGPULowering::computeActiveAndInactiveParDims(Operation *op,
1674 MLIRContext *ctx = computeRegion->getContext();
1676 mlir::acc::GPUParallelDimAttr routineParDim;
1678 FunctionOpInterface funcOp =
1679 computeRegion->getParentOfType<FunctionOpInterface>();
1680 routineParDim = getSpecializedRoutineDim(funcOp, defaultPolicy);
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);
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()) {
1701 launchParDims = computeRegion.getLaunchParDims();
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())
1710 if (!llvm::is_contained(activeParDims, launchParDim))
1711 inactiveParDims.push_back(launchParDim);
1713 return std::pair{activeParDims, inactiveParDims};
1717 SmallVector<mlir::acc::GPUParallelDimAttr> ancestorParDims =
1718 getAncestorParDims(op);
1723 bool noStructuralAncestorParDims =
1724 llvm::none_of(ancestorParDims, [](
auto pd) {
return !pd.isSeq(); });
1726 if (routineParDim) {
1727 if (routineParDim.isThreadX()) {
1729 mlir::acc::GPUParallelDimAttr::threadYDim(ctx));
1732 mlir::acc::GPUParallelDimAttr::blockXDim(ctx));
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()) {
1752 if (acc::ReductionCombineOp combineOp =
1753 dyn_cast<acc::ReductionCombineOp>(user)) {
1754 if (combineOp.getSrcMemref() == privateLocalOp.
getResult()) {
1755 for (mlir::acc::GPUParallelDimAttr parDim :
1761 if (
auto combineRegionOp =
1762 dyn_cast<acc::ReductionCombineRegionOp>(user)) {
1763 if (combineRegionOp.getSrcVar() == privateLocalOp.getResult()) {
1764 for (mlir::acc::GPUParallelDimAttr parDim :
1776 acc::PrivateType privTy =
1777 cast<acc::PrivateType>(privateLocalOp.getPrivatized().getType());
1779 privTy.getBaseTy(), computeRegion->getParentOfType<ModuleOp>());
1780 if (!baseTy.hasStaticShape()) {
1781 GPUParallelDimsAttr ownParDims =
1782 getPrivateParDims(privateLocalOp, computeRegion);
1784 for (GPUParallelDimAttr parDim : ownParDims.getArray())
1789 bool hasBlock =
false;
1790 for (mlir::acc::GPUParallelDimAttr parDim : ancestorParDims)
1791 if (parDim.isAnyBlock())
1794 mlir::acc::GPUParallelDimAttr lowestParDim =
1795 mlir::acc::GPUParallelDimAttr::threadXDim(ctx);
1797 ThreadYBroadeningInfo threadYInfo =
1798 analyzeThreadYBroadening(*block, computeRegion);
1800 auto applyCombineParDims =
1801 [&](ArrayRef<mlir::acc::GPUParallelDimAttr> combineParDims) {
1802 for (mlir::acc::GPUParallelDimAttr parDim : combineParDims)
1806 block->
walk([&](Operation *op) -> WalkResult {
1812 auto addPrivateStoreParDims = [&](Value
target) {
1813 if (
auto privateLocalOp = getPrivateLocalForMemref(
target)) {
1814 GPUParallelDimsAttr parDimsAttr =
1815 getPrivateParDims(privateLocalOp, computeRegion);
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))
1830 if (
auto memEffects = dyn_cast<MemoryEffectOpInterface>(op)) {
1831 SmallVector<MemoryEffects::EffectInstance> effects;
1832 memEffects.getEffects(effects);
1834 if (isa<MemoryEffects::Write>(effect.getEffect()) &&
1836 addPrivateStoreParDims(effect.getValue());
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;
1847 lowestParDim = parDim.getOneHigher();
1853 if (acc::ReductionCombineOp reductionCombineOp =
1854 dyn_cast<acc::ReductionCombineOp>(op)) {
1855 if (
failed(applyCombineParDims(
1859 if (acc::ReductionCombineRegionOp combineRegionOp =
1860 dyn_cast<acc::ReductionCombineRegionOp>(op)) {
1861 if (
failed(applyCombineParDims(
1868 if (acc::ReductionAccumulateArrayOp accArrayOp =
1869 dyn_cast<acc::ReductionAccumulateArrayOp>(op)) {
1870 for (mlir::acc::GPUParallelDimAttr parDim :
1871 accArrayOp.getParDims().getArray()) {
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;
1887 "operations in the same predicate region require incompatible "
1888 "ThreadY predication");
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()) {
1905 launchParDims = computeRegion.getLaunchParDims();
1909 SmallVector<mlir::acc::GPUParallelDimAttr> activeParDims, inactiveParDims;
1910 for (mlir::acc::GPUParallelDimAttr launchParDim : launchParDims) {
1911 if (launchParDim.getOrder() < lowestParDim.getOrder())
1913 if (llvm::find(ancestorParDims, launchParDim) != ancestorParDims.end() ||
1914 (launchParDim.isAnyBlock() &&
1915 (noStructuralAncestorParDims || hasBlock))) {
1916 activeParDims.push_back(launchParDim);
1918 inactiveParDims.push_back(launchParDim);
1922 return std::pair{activeParDims, inactiveParDims};
1925Value ACCCGToGPULowering::emitPredicate(
1926 Location loc, SmallVector<mlir::acc::GPUParallelDimAttr> &inactiveParDims) {
1928 for (mlir::acc::GPUParallelDimAttr inactiveParDim : inactiveParDims) {
1929 Value threadId = getGPUThreadIdFor(inactiveParDim.getProcessor());
1931 Value zero = arith::ConstantOp::create(rewriter, loc, zeroAttr);
1932 Value cmp = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
1935 predicate = arith::AndIOp::create(rewriter, loc, cmp, predicate);
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())
1948 if (parDim.isThreadY())
1950 if (parDim.isThreadX())
1954 if (hasAnyBlock || hasThreadY)
1955 emitGPUBarrierWorkgroup(rewriter, loc);
1956 else if (hasThreadX)
1957 createPerRowBarrier(loc);
1960void ACCCGToGPULowering::createPerRowBarrier(Location loc) {
1963 if (isSingleThreadWorkerLaunch())
1969 if (isWorkerOnlyShuffleLaunch() && staticBlockDimX <
options.subgroupSize) {
1970 emitGPUBarrierRow(rewriter, loc, staticBlockDimX,
options.subgroupSize);
1974 hasThreadYBarrier =
true;
1976 if (staticBlockDimX <=
options.subgroupSize) {
1977 emitGPUBarrierSubgroup(rewriter, loc);
1981 if (
options.deviceType != mlir::acc::DeviceType::Nvidia) {
1984 "per-row barrier to support worker parallelism on non-NVIDIA device");
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);
2005 Value isSingleWorker = arith::CmpIOp::create(
2006 rewriter, loc, arith::CmpIPredicate::eq, blockDimY, cst1);
2008 auto outerIf = scf::IfOp::create(rewriter, loc, isSingleWorker,
2013 emitGPUBarrierWorkgroup(rewriter, loc);
2017 Value cstSubgroupSize =
2019 Value isSubgroupSized = arith::CmpIOp::create(
2020 rewriter, loc, arith::CmpIPredicate::ule, blockDimX, cstSubgroupSize);
2022 auto innerIf = scf::IfOp::create(rewriter, loc, isSubgroupSized,
2028 emitGPUBarrierSubgroup(rewriter, loc);
2035 Value threadYId = gpu::ThreadIdOp::create(
2036 rewriter, loc, rewriter.
getIndexType(), gpu::Dimension::y);
2037 Value barrierId = arith::AddIOp::create(rewriter, loc, threadYId, cst1);
2040 arith::IndexCastOp::create(rewriter, loc, i32Ty, barrierId);
2041 Value numberOfThreads32 =
2042 arith::IndexCastOp::create(rewriter, loc, i32Ty, blockDimX);
2046 assert(
options.deviceType == mlir::acc::DeviceType::Nvidia);
2047 NVVM::BarrierOp::create(rewriter, loc, barrierId32, numberOfThreads32);
2056static bool hasSubsequentLoopSibling(Operation *loopOp) {
2057 for (Operation *next = loopOp->getNextNode(); next;
2058 next =
next->getNextNode()) {
2059 if (isa<scf::ParallelOp, scf::ForOp>(next))
2061 bool nested =
false;
2062 next->walk([&](Operation *op) {
2063 if (isa<scf::ParallelOp, scf::ForOp>(op)) {
2076static LoopLikeOpInterface findFirstSequentialLoop(Operation *op) {
2077 auto isAllSequentialParDims = [](scf::ParallelOp par) ->
bool {
2079 if (!pd || pd.getArray().empty())
2081 return llvm::all_of(pd.getArray(), [](mlir::acc::GPUParallelDimAttr d) {
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);
2108static bool isLoopBodyClosureOp(Operation *op) {
2109 return isa<scf::ReduceOp, scf::YieldOp, acc::YieldOp>(op);
2114static bool isDeferredBarrierFlushPoint(Operation *op) {
2115 if (isLoopBodyClosureOp(op))
2119 if (isa<scf::ForOp>(op))
2121 if (scf::ParallelOp parallelOp = dyn_cast<scf::ParallelOp>(op)) {
2123 if (mlir::acc::GPUParallelDimsAttr parDims =
2125 if (parDims.getArray().size() == 1 &&
2126 parDims.getArray().front().isSeq()) {
2138static bool hasTrailingSideEffectSiblings(Operation *loopOp) {
2139 for (Operation *next = loopOp->getNextNode(); next;
2140 next =
next->getNextNode()) {
2141 return !isLoopBodyClosureOp(next);
2165void ACCCGToGPULowering::createBarrierAfterSeqLoop(Operation *loopOp) {
2167 auto getParentParallel = [&](Operation *op) -> scf::ParallelOp {
2169 if (parent && computeRegion->isAncestor(parent))
2173 scf::ParallelOp wsLoop = getParentParallel(loopOp);
2181 if (mayWriteSharedMemory(loopOp) && hasSubsequentLoopSibling(loopOp))
2182 emitGPUBarrierWorkgroup(rewriter, loopOp->
getLoc());
2188 wsParDims.getArray().size() == 1 && wsParDims.getArray().front().isSeq();
2195 bool hasThreadSubLoop =
false;
2196 loopOp->
walk([&](scf::ParallelOp innerPar) -> WalkResult {
2197 if (innerPar.getOperation() == loopOp)
2200 for (
auto d : dims.getArray()) {
2201 if (d.isThreadX() || d.isThreadY()) {
2202 hasThreadSubLoop =
true;
2208 if (!hasThreadSubLoop)
2210 scf::ParallelOp threadLoop = getParentParallel(wsLoop);
2213 scf::ParallelOp blockLoop = getParentParallel(threadLoop);
2216 mlir::acc::GPUParallelDimsAttr parDimsAttr =
2218 if (parDimsAttr.hasOnlyBlockLevel())
2219 createBarrier(loopOp->
getLoc(), parDimsAttr);
2225 scf::ParallelOp seqLoop = getParentParallel(wsLoop);
2234 if (mayWriteSharedMemory(loopOp) && hasSubsequentLoopSibling(wsLoop))
2235 emitGPUBarrierWorkgroup(rewriter, loopOp->
getLoc());
2238 if (scf::ParallelOp outerParLoop = getParentParallel(seqLoop)) {
2239 mlir::acc::GPUParallelDimsAttr parDimsAttr =
2241 if (parDimsAttr.hasOnlyBlockLevel()) {
2242 createBarrier(loopOp->
getLoc(), parDimsAttr);
2243 }
else if (parDimsAttr.hasOnlyThreadYLevel()) {
2244 createPerRowBarrier(loopOp->
getLoc());
2245 }
else if (parDimsAttr && parDimsAttr.isSeq()) {
2249 for (scf::ParallelOp gangLoop = getParentParallel(outerParLoop); gangLoop;
2250 gangLoop = getParentParallel(gangLoop)) {
2251 mlir::acc::GPUParallelDimsAttr gangDims =
2253 if (gangDims.hasOnlyBlockLevel()) {
2254 createBarrier(loopOp->
getLoc(), gangDims);
2257 if (!gangDims.isSeq())
2271 mlir::acc::GPUParallelDimsAttr parDimsAttr =
2273 if (parDimsAttr.hasOnlyBlockLevel() && mayWriteSharedMemory(loopOp)) {
2274 createBarrier(loopOp->
getLoc(), parDimsAttr);
2278bool ACCCGToGPULowering::mayWriteSharedMemory(Operation *loopOp) {
2280 loopOp->
walk([&](memref::StoreOp storeOp) {
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)
2292 if (acc::PrivateLocalOp privateLocal =
2293 dyn_cast<acc::PrivateLocalOp>(def)) {
2294 acc::PrivatizeOp privatizeOp =
2302 if (mlir::acc::GPUParallelDimsAttr parDims =
2303 privatizeOp.getParDimsAttr()) {
2304 bool hasBlock =
false, hasThread =
false;
2305 for (mlir::acc::GPUParallelDimAttr d : parDims.getArray()) {
2308 if (d.isThreadX() || d.isThreadY())
2311 if (hasBlock && !hasThread) {
2328static bool isAllocatedInside(Value memref, Operation *scope) {
2333 if (
auto effectOp = dyn_cast<MemoryEffectOpInterface>(def))
2334 if (effectOp.getEffectOnValue<MemoryEffects::Allocate>(v))
2338 if (ViewLikeOpInterface viewLike = dyn_cast<ViewLikeOpInterface>(def))
2339 v = viewLike.getViewSource();
2348static bool isRedundantSequentialLoop(Operation *op) {
2349 if (isa<scf::ForOp, scf::WhileOp>(op))
2351 scf::ParallelOp par = dyn_cast<scf::ParallelOp>(op);
2355 return dims && !dims.getArray().empty() &&
2356 llvm::all_of(dims.getArray(), [](mlir::acc::GPUParallelDimAttr d) {
2368static Value getStorageRoot(Value memref) {
2371 auto onlyNonMemoryEffects = [](Operation *op) {
2372 MemoryEffectOpInterface effectOp = dyn_cast<MemoryEffectOpInterface>(op);
2375 SmallVector<MemoryEffects::EffectInstance> effects;
2376 effectOp.getEffects(effects);
2378 return e.
getResource() != SideEffects::DefaultResource::get();
2385 Operation *owner = cast<BlockArgument>(v).getOwner()->getParentOp();
2386 if (isa<scf::ForOp, scf::WhileOp>(owner))
2391 if (
auto computeOp = dyn_cast<acc::ComputeRegionOp>(owner))
2392 if (Value operand = computeOp.getOperand(cast<BlockArgument>(v)))
2393 if (Value outerRoot = getStorageRoot(operand))
2397 if (
auto effectOp = dyn_cast<MemoryEffectOpInterface>(def))
2398 if (effectOp.getEffectOnValue<MemoryEffects::Allocate>(v))
2403 if (ViewLikeOpInterface viewLike = dyn_cast<ViewLikeOpInterface>(def))
2404 v = viewLike.getViewSource();
2410bool ACCCGToGPULowering::mayAccessSharedMemory(Operation *root,
bool reads,
2411 bool writes,
bool workerLevel,
2412 Operation *localScope,
2414 SharedStorage *collect,
2415 const SharedStorage *filter) {
2420 auto sharedAccess = [&](Value
target) {
2421 Value storage =
target ? getStorageRoot(
target) : Value();
2422 if (filter && storage && !filter->unknown &&
2423 !filter->roots.contains(storage))
2429 collect->roots.insert(storage);
2431 collect->unknown =
true;
2434 root->
walk([&](Operation *op) {
2435 if (op->
hasTrait<OpTrait::IsTerminator>())
2440 if (isa<acc::ReductionAccumulateOp, acc::ReductionCombineOp,
2441 acc::ReductionCombineRegionOp>(op))
2443 MemoryEffectOpInterface effectOp = dyn_cast<MemoryEffectOpInterface>(op);
2447 if (op->
hasTrait<OpTrait::HasRecursiveMemoryEffects>())
2449 return sharedAccess(Value());
2451 SmallVector<MemoryEffects::EffectInstance> effects;
2452 effectOp.getEffects(effects);
2455 (writes && isa<MemoryEffects::Write>(effect.getEffect())) ||
2456 (reads && isa<MemoryEffects::Read>(effect.getEffect()));
2459 Value
target = effect.getValue();
2461 PrivateMemScope scope = getPrivateScopeForMemref(
target);
2462 if (scope == PrivateMemScope::Thread ||
2463 (workerLevel && scope == PrivateMemScope::Worker))
2465 if (localScope && isAllocatedInside(
target, localScope))
2468 if (sharedAccess(
target).wasInterrupted())
2476bool ACCCGToGPULowering::needsBarrierAfterThreadLoop(scf::ParallelOp loop) {
2478 if (!loopDims || loopDims.getArray().size() != 1)
2480 mlir::acc::GPUParallelDimAttr loopDim = loopDims.getArray().front();
2481 if (!loopDim.isThreadX() && !loopDim.isThreadY())
2483 bool workerLevel = loopDim.isThreadY();
2488 for (Operation *parent = loop->getParentOp();
2489 parent && parent != computeRegion.getOperation();
2490 parent = parent->getParentOp()) {
2491 scf::ParallelOp parentLoop = dyn_cast<scf::ParallelOp>(parent);
2494 mlir::acc::GPUParallelDimsAttr parentDims =
2498 for (mlir::acc::GPUParallelDimAttr dim : parentDims.getArray())
2499 if (dim.isThreadY())
2506 bool hasOwnTile =
false;
2507 loop->walk([&](acc::GPUSharedMemoryOp) {
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;
2525 if (!inSequentialNest)
2534 SharedStorage written, touched;
2535 mayAccessSharedMemory(loop,
false,
true, workerLevel,
2536 loop,
nullptr, &written);
2537 mayAccessSharedMemory(loop,
true,
false, workerLevel,
2538 loop,
nullptr, &touched);
2539 touched.insert(written);
2540 if (touched.empty())
2542 bool loopWrites = !written.empty();
2545 auto conflictsWithLoop = [&](Operation *op, Operation *localScope,
2546 Operation *ignore) {
2547 if (loopWrites && mayAccessSharedMemory(
2548 op,
true,
false, workerLevel,
2549 localScope, ignore,
nullptr, &written))
2551 return mayAccessSharedMemory(op,
false,
true,
2552 workerLevel, localScope, ignore,
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,
nullptr,
nullptr))
2565 Operation *parent = cur->getParentOp();
2566 if (!parent || parent == computeRegion.getOperation())
2568 if (!isRedundantSequentialLoop(parent))
2571 if (isa<scf::WhileOp>(parent))
2576 for (Operation *prev = &cur->getBlock()->front(); prev;
2577 prev = prev->getNextNode()) {
2579 if (conflictsWithLoop(prev,
nullptr,
nullptr))
2588 if (loopWrites && mayAccessSharedMemory(
2589 loop,
true,
false, workerLevel,
2591 nullptr,
nullptr, &written))
2594 if (cur != loop && conflictsWithLoop(cur, cur, loop))
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()) {
2617 for (mlir::acc::GPUParallelDimAttr d : computeRegion.getLaunchParDims())
2621 return PrivateMemScope::Gang;
2622 return PrivateMemScope::Thread;
2625 return PrivateMemScope::Thread;
2626 if (hasBlock && hasThreadY)
2627 return PrivateMemScope::Worker;
2629 return PrivateMemScope::Gang;
2630 return PrivateMemScope::Thread;
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)
2644 if (acc::PrivateLocalOp privateLocal = dyn_cast<acc::PrivateLocalOp>(def))
2645 return privateLocal;
2646 getStorageSourceOperands(def, worklist);
2651PrivateMemScope ACCCGToGPULowering::getPrivateScopeForMemref(Value memref) {
2652 if (
auto privateLocal = getPrivateLocalForMemref(memref))
2653 return getPrivateMemScope(
getPrivatizeOp(privateLocal, computeRegion));
2654 return PrivateMemScope::None;
2657acc::PrivatizeOp ACCCGToGPULowering::getPrivatizeForMemref(Value memref) {
2658 if (
auto privateLocal = getPrivateLocalForMemref(memref))
2660 return acc::PrivatizeOp();
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)
2670 acc::PrivatizeOp privatize = getPrivatizeForMemref(storeOp.getMemref());
2673 if (scope == PrivateMemScope::Gang)
2674 gangPrivatizes.insert(privatize.getOperation());
2676 workerPrivatizes.insert(privatize.getOperation());
2680bool ACCCGToGPULowering::isMatchingPrivateMemref(
2681 Value memref, PrivateMemScope storeScope,
2682 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes) {
2683 if (getPrivateScopeForMemref(memref) != storeScope)
2685 acc::PrivatizeOp usePrivatize = getPrivatizeForMemref(memref);
2686 return usePrivatize && storePrivatizes.contains(usePrivatize.getOperation());
2689bool ACCCGToGPULowering::hasParallelPrivateReuse(
2690 LoopLikeOpInterface seqLoopOp, Operation *skipOp,
2691 PrivateMemScope storeScope,
2692 const llvm::SmallPtrSetImpl<Operation *> &storePrivatizes) {
2693 if (storePrivatizes.empty())
2696 bool hasParallelPrivateUse =
false;
2697 seqLoopOp.getOperation()->walk([&](Operation *op) {
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();
2710 if (!isMatchingPrivateMemref(memref, storeScope, storePrivatizes))
2713 bool insideNestedParallel =
false;
2714 for (Operation *p = op->
getParentOp(); p && p != seqLoopOp.getOperation();
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) {
2722 insideNestedParallel =
true;
2728 if (!insideNestedParallel)
2731 hasParallelPrivateUse =
true;
2735 return hasParallelPrivateUse;
2739ACCCGToGPULowering::needsPreStoreReuseBarrier(acc::PredicateRegionOp interOp) {
2743 LoopLikeOpInterface seqLoopOp = findFirstSequentialLoop(interOp);
2745 return PrivateMemScope::None;
2749 llvm::SmallPtrSet<Operation *, 4> gangPrivatizes, workerPrivatizes;
2750 collectSharedPrivateStores(interOp, gangPrivatizes, workerPrivatizes);
2756 if (hasParallelPrivateReuse(seqLoopOp, interOp, PrivateMemScope::Gang,
2758 return PrivateMemScope::Gang;
2759 if (hasParallelPrivateReuse(seqLoopOp, interOp, PrivateMemScope::Worker,
2761 return PrivateMemScope::Worker;
2762 return PrivateMemScope::None;
2765bool ACCCGToGPULowering::needsInLoopReuseBarrier(Operation *loopOp) {
2770 if (scf::ParallelOp par = dyn_cast<scf::ParallelOp>(loopOp))
2777 if (!hasThreadLevelRoutineCall)
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;
2790 if (!callsThreadLevelRoutine)
2796 llvm::SmallPtrSet<Operation *, 4> storedPrivatizes, workerPrivatizes;
2797 collectSharedPrivateStores(loopOp, storedPrivatizes, workerPrivatizes);
2798 if (storedPrivatizes.empty())
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,
2816 if (!reusesGangPrivate)
2823 p && p != computeRegion.getOperation(); p = p->
getParentOp()) {
2824 scf::ParallelOp par = dyn_cast<scf::ParallelOp>(p);
2828 for (mlir::acc::GPUParallelDimAttr d : parDims.getArray())
2829 if (d.isThreadX() || d.isThreadY())
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();
2841 std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
2842 SmallVector<mlir::acc::GPUParallelDimAttr>>
2843 parDimsPair = computeActiveAndInactiveParDims(
2844 interOp, &interOp.getRegion().front());
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();
2863 bool hasThreadXInInactive =
2864 llvm::any_of(parDimsPair.second, [](mlir::acc::GPUParallelDimAttr pd) {
2865 return pd.isThreadX();
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;
2885 if (!hasThreadXInActive && !hasThreadXInInactive &&
2886 !regionHasThreadLevelRoutineCall) {
2887 parDimsPair.second.push_back(threadXParDim);
2891 Value predicate = emitPredicate(loc, parDimsPair.second);
2894 if (!predicate && llvm::all_of(computeRegion.getLaunchParDims(),
2895 [](mlir::acc::GPUParallelDimAttr pd) {
2896 return pd.isAnyBlock();
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;
2913 auto emitReconvergenceBarrier = [&]() {
2914 if (isInsideThreadXLoop) {
2916 }
else if (isInsideThreadYLoop) {
2921 bool predicatesThreadX = llvm::any_of(
2923 [](mlir::acc::GPUParallelDimAttr pd) { return pd.isThreadX(); });
2924 if (predicatesThreadX)
2925 createPerRowBarrier(loc);
2928 }
else if (!parDimsPair.first.empty()) {
2930 createBarrier(loc, mlir::acc::GPUParallelDimsAttr::get(
2931 interOp->getContext(), parDimsPair.first));
2934 createBarrier(loc, mlir::acc::GPUParallelDimsAttr::get(
2935 interOp->getContext(), parDimsPair.second));
2947 PrivateMemScope scope = needsPreStoreReuseBarrier(interOp);
2948 if (scope == PrivateMemScope::Gang)
2949 emitGPUBarrierWorkgroup(rewriter, loc);
2950 else if (scope == PrivateMemScope::Worker)
2951 createPerRowBarrier(loc);
2953 auto ifOp = scf::IfOp::create(rewriter, loc, predicate,
2955 Region &thenRegion = ifOp.getThenRegion();
2959 for (
auto &bodyOp : interOp.getRegion().front().getOperations()) {
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();
2973 Block *epilogueBlock = interOp->getBlock();
2974 auto findBlockAccLoad =
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();
2988 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
2989 accOp.getReductionOperator(),
2990 accOp.getValue().getType(), accOp.getLoc());
2992 failedReductionKind =
true;
2993 return std::nullopt;
2999 return std::nullopt;
3002 if (
auto kind = self(self, operand))
3004 return std::nullopt;
3006 blockReduceKind = findBlockAccLoad(findBlockAccLoad, storeVal);
3008 if (failedReductionKind)
3012 if (blockReduceKind && getPrivateScopeForMemref(storeOp.getMemref()) !=
3013 PrivateMemScope::None)
3014 blockReduceKind.reset();
3015 if (blockReduceKind) {
3018 bool threadIsActive = llvm::any_of(
3019 parDimsPair.first, [](mlir::acc::GPUParallelDimAttr pd) {
3020 return !pd.isAnyBlock();
3022 if (!threadIsActive &&
3023 !isa_and_nonnull<memref::AllocaOp>(
3024 unwrapMemRefConversion(memref).getDefiningOp())) {
3030 MemRefType memrefTy = cast<MemRefType>(memref.
getType());
3032 SmallVector<Value> initIndices;
3033 for (Value idx : storeOp.getIndices())
3036 OpBuilder::InsertionGuard guard(rewriter);
3037 Block &launchBody = launch.getBody().front();
3038 Operation *insertBefore =
nullptr;
3040 launchBody.
walk([&](scf::ParallelOp parOp) -> WalkResult {
3041 for (Operation *parent = parOp->getParentOp(); parent;
3043 if (parent == launch.getOperation())
3045 if (isa<scf::ParallelOp>(parent))
3048 insertBefore = parOp.getOperation();
3054 std::function<bool(Value)> fromLaunch = [&](Value v) ->
bool {
3055 if (
auto arg = dyn_cast<BlockArgument>(v))
3056 return launch->isAncestor(arg.getOwner()->getParentOp());
3058 if (!launch->isAncestor(def) ||
3059 def->
hasTrait<OpTrait::ConstantLike>())
3065 if (!fromLaunch(memref) &&
3066 llvm::none_of(initIndices, fromLaunch)) {
3069 Value token = launch.getAsyncToken();
3070 auto initLaunch = gpu::LaunchOp::create(
3071 rewriter, loc, one, one, one, one, one, one,
3073 token ? token.
getType() : Type(),
3074 launch.getAsyncDependencies());
3076 &initLaunch.getBody().front());
3078 gpu::TerminatorOp::create(rewriter, loc));
3079 }
else if (insertBefore)
3089 DominanceInfo domInfo(launch);
3090 IRMapping initMapping;
3091 std::function<Value(Value)> materialize =
3092 [&](Value val) -> Value {
3093 Operation *defOp = val.getDefiningOp();
3104 materialize(operand);
3105 Operation *cloned = rewriter.
clone(*defOp, initMapping);
3106 for (
auto [orig, clonedRes] :
3108 initMapping.
map(orig, clonedRes);
3110 return initMapping.
lookup(val);
3112 Value initMemref = materialize(memref);
3113 for (
auto &idx : initIndices)
3114 idx = materialize(idx);
3116 rewriter, loc, memrefTy.getElementType(), *blockReduceKind,
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);
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,
3132 initIf.getThenRegion().back().getTerminator());
3133 memref::StoreOp::create(rewriter, loc, identityVal, initMemref,
3136 gpu::BarrierOp::create(rewriter, loc);
3138 SmallVector<Value> atomicIndices;
3139 for (Value idx : storeOp.getIndices())
3141 constructAtomicAccumulation(loc, memref, atomicIndices, input,
3150 emitReconvergenceBarrier();
3153 for (
auto &bodyOp : interOp.getRegion().front().getOperations())
3176Value ACCCGToGPULowering::allocatePrivatizeHeapStorage(
3177 acc::PrivatizeOp privatize, MemRefType baseTy,
3179 Location loc = privatize.getLoc();
3181 memref::AllocOp::create(rewriter, loc, baseTy, mappedDynamicSizes);
3182 recordGlobalMemory(privatize);
3183 OpBuilder::InsertionGuard guard(rewriter);
3187 memref::DeallocOp::create(rewriter, loc, mem);
3189 mapping.
map(privatize.getResult(), mem);
3192 if (!privatize->getParentOfType<acc::ComputeRegionOp>())
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());
3208 Operation *privatizeUser = getOnlyUser(tracked);
3209 assert(privatizeUser &&
"expected PrivateLocalOp user for privatize");
3210 acc::PrivateLocalOp privateLocalUser =
3211 dyn_cast<acc::PrivateLocalOp>(privatizeUser);
3213 std::pair<SmallVector<mlir::acc::GPUParallelDimAttr>,
3214 SmallVector<mlir::acc::GPUParallelDimAttr>>
3215 parDimsPair = computeActiveAndInactiveParDims(privatizeUser,
nullptr);
3217 if (!privatize.getParDimsAttr()) {
3218 privatize.setParDimsAttr(mlir::acc::GPUParallelDimsAttr::get(
3222 Location loc = privatize->getLoc();
3223 acc::PrivateType privTy = cast<acc::PrivateType>(privatize.getType());
3224 ModuleOp module = computeRegion->getParentOfType<ModuleOp>();
3227 gpu::GPUFuncOp gpuFuncOp = computeRegion->getParentOfType<gpu::GPUFuncOp>();
3232 privatize->getParentOfType<acc::ComputeRegionOp>() != computeRegion) {
3233 return privatize.getResult();
3236 bool threadXActive =
3237 llvm::any_of(parDimsPair.first, [](mlir::acc::GPUParallelDimAttr parDim) {
3238 return parDim.isThreadX();
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();
3249 return privatize.getResult();
3257 bool threadYIsActive =
3258 llvm::any_of(parDimsPair.first, [](mlir::acc::GPUParallelDimAttr parDim) {
3259 return parDim.isThreadY();
3272 bool needsWorkgroupBarrier =
false;
3274 FunctionOpInterface funcOp =
3275 computeRegion->getParentOfType<FunctionOpInterface>();
3276 mlir::acc::GPUParallelDimAttr routineParDim =
3277 getSpecializedRoutineDim(funcOp, defaultPolicy);
3278 if (routineParDim.isThreadX()) {
3281 threadYIsActive =
true;
3282 }
else if (routineParDim.isThreadY()) {
3285 needsWorkgroupBarrier =
true;
3286 }
else if (routineParDim.isAnyBlock()) {
3287 needsWorkgroupBarrier =
true;
3291 llvm::SmallVector<Value> mappedDynamicSizes;
3292 for (
auto dynamicSize : privatize.getDynamicSizes()) {
3294 mappedDynamicSizes.push_back(mappedDynamicSize);
3297 computeRegion.isEffectivelySerial()) {
3298 if (mappedDynamicSizes.empty()) {
3301 memref::AllocaOp::create(rewriter, privatize->getLoc(), baseTy);
3302 recordThreadPrivate(privateLocalUser);
3303 mapping.
map(privatize.getResult(), alloca.getResult());
3304 return alloca.getResult();
3307 return allocatePrivatizeHeapStorage(privatize, baseTy, mappedDynamicSizes);
3310 if (threadXActive) {
3315 return allocatePrivatizeHeapStorage(privatize, baseTy, mappedDynamicSizes);
3320 SmallVector<mlir::acc::GPUParallelDimAttr> predicateDims;
3321 for (
auto parDim : parDimsPair.second) {
3323 if (threadYIsActive && parDim.isThreadY())
3325 predicateDims.push_back(parDim);
3327 Value predicate = emitPredicate(loc, predicateDims);
3329 predicate = arith::ConstantOp::create(
3332 auto ifOp = scf::IfOp::create(rewriter, loc, predicate,
3334 Region &thenRegion = ifOp.getThenRegion();
3337 auto mem = memref::AllocOp::create(rewriter, privatize->getLoc(), baseTy,
3338 mappedDynamicSizes);
3339 recordGlobalMemory(privatize);
3341 gpu::AddressSpaceAttr sharedMemoryAddressSpace = gpu::AddressSpaceAttr::get(
3342 computeRegion->getContext(), gpu::GPUDialect::getWorkgroupAddressSpace());
3346 constexpr int64_t kMaxThreadY = 32;
3347 MemRefType sharedMemTy =
3349 ? MemRefType::get({kMaxThreadY}, baseTy, MemRefLayoutAttrInterface{},
3350 sharedMemoryAddressSpace)
3351 : MemRefType::
get({}, baseTy, MemRefLayoutAttrInterface{},
3352 sharedMemoryAddressSpace);
3355 bool reuseBroadcast = !gpuFuncOp.isKernel();
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;
3364 mlir::acc::GPUParallelDimAttr dim =
3365 needsWorkgroupBarrier
3366 ? mlir::acc::GPUParallelDimAttr::threadYDim(rewriter.
getContext())
3367 : mlir::
acc::GPUParallelDimAttr::threadXDim(rewriter.
getContext());
3369 loc, mlir::acc::GPUParallelDimsAttr::get(rewriter.
getContext(), {dim}));
3371 alloca = gpuFuncOp.addWorkgroupAttribution(sharedMemTy,
3376 unsigned index = gpuFuncOp.getNumWorkgroupAttributions() - 1;
3377 gpuFuncOp.setWorkgroupAttributionAttr(
index,
3378 LLVM::LLVMDialect::getAlignAttrName(),
3381 privatizeBroadcastCache[sharedMemTy] = alloca;
3384 if (threadYIsActive) {
3385 Value threadYId = getThreadId(loc, gpu::Dimension::y);
3386 memref::StoreOp::create(rewriter, privatize->getLoc(), mem, alloca,
3389 memref::StoreOp::create(rewriter, privatize->getLoc(), mem, alloca);
3395 if (needsWorkgroupBarrier) {
3396 mlir::acc::GPUParallelDimsAttr threadYDimsAttr =
3397 mlir::acc::GPUParallelDimsAttr::get(
3399 {mlir::acc::GPUParallelDimAttr::threadYDim(rewriter.getContext())});
3400 createBarrier(loc, threadYDimsAttr);
3403 mlir::acc::GPUParallelDimsAttr threadXDimsAttr =
3404 mlir::acc::GPUParallelDimsAttr::get(
3406 {mlir::acc::GPUParallelDimAttr::threadXDim(rewriter.getContext())});
3407 createBarrier(loc, threadXDimsAttr);
3411 if (threadYIsActive) {
3412 Value threadYId = getThreadId(loc, gpu::Dimension::y);
3413 load = memref::LoadOp::create(rewriter, privatize->getLoc(), alloca,
3416 load = memref::LoadOp::create(rewriter, privatize->getLoc(), alloca,
3420 mapping.
map(privatize.getResult(),
load);
3424 if (!privatize->getParentOfType<acc::ComputeRegionOp>())
3428 if (needsWorkgroupBarrier) {
3429 mlir::acc::GPUParallelDimsAttr workerDimsAttr =
3430 mlir::acc::GPUParallelDimsAttr::get(
3432 {mlir::acc::GPUParallelDimAttr::threadYDim(rewriter.getContext())});
3433 createBarrier(loc, workerDimsAttr);
3435 mlir::acc::GPUParallelDimsAttr vectorDimsAttr =
3436 mlir::acc::GPUParallelDimsAttr::get(
3438 {mlir::acc::GPUParallelDimAttr::threadXDim(rewriter.getContext())});
3439 createBarrier(loc, vectorDimsAttr);
3441 auto ifOp2 = scf::IfOp::create(rewriter, loc, predicate,
3443 Region &thenRegion2 = ifOp2.getThenRegion();
3446 memref::DeallocOp::create(rewriter, privatize->getLoc(),
load);
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>();
3466 MemRefType byteMemrefTy =
3467 MemRefType::get({ShapedType::kDynamic}, rewriter.
getI8Type());
3469 acc::PrivatizeOp privatizeOp =
getPrivatizeOp(privateLocal, computeRegion);
3471 if (privatizeOp->getParentOfType<acc::ComputeRegionOp>() == computeRegion) {
3475 privateLocal.getType());
3476 mapping.
map(privateLocal.getResult(),
result);
3484 acc::ReductionAccumulateArrayOp arrayAccum =
3485 perThreadArrayReductionAccum(privateLocal.getResult());
3487 (arrayAccum && storageHasThreadX(privateLocal, computeRegion))) &&
3488 canUseStackAlloca(baseTy, loc,
options.maxThreadPrivateStack)) {
3489 Value alloca = memref::AllocaOp::create(rewriter, loc, baseTy);
3490 recordThreadPrivate(privateLocal);
3492 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
3493 arrayAccum.getReductionOperator(), baseTy.getElementType(), loc);
3496 initPerThreadArrayAccum(rewriter, loc, alloca, baseTy, *kind);
3499 privateLocal.getType());
3500 mapping.
map(privateLocal.getResult(), mem);
3506 std::optional<int64_t>
copies =
3507 sharedMemCopies ? sharedMemCopies
3508 : isEligibleForSharedMemory(privateLocal, baseTy);
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())
3515 int64_t upperBound = elementSize * numElements * numCopies;
3517 if (tryAllocateSharedMemory(upperBound)) {
3518 std::string varName =
3520 sharedMemPrivateVarNames.push_back(varName.empty() ?
"(*)" : varName);
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(
3536 privateLocal.getType());
3538 mapping.
map(privateLocal.getResult(),
result);
3543 OpBuilder::InsertionGuard guard(rewriter);
3545 inputMem = processPrivatize(privatizeOp);
3549 assert(inputMem &&
"expected input mem to be mapped");
3551 privateLocal.getType());
3552 mapping.
map(privateLocal.getResult(),
result);
3558 SmallVector<int64_t> viewShape;
3560 SmallVector<Value> viewDynSizes;
3562 SmallVector<OpFoldResult> subviewOffset;
3565 SmallVector<OpFoldResult> subviewSizes;
3567 SmallVector<int64_t> subviewStrides;
3569 SmallVector<int64_t> subviewShape;
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);
3583 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
3584 arrayAccum.getReductionOperator(), baseTy.getElementType(), loc);
3587 initPerThreadArrayAccum(rewriter, loc, alloca, baseTy, *kind);
3590 privateLocal.getType());
3591 mapping.
map(privateLocal.getResult(), mem);
3595 if (parDimsPair.first.empty()) {
3599 mlir::acc::GPUParallelDimAttr::blockXDim(privateLocal.getContext()));
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));
3610 SmallVector<Value> innerDynSizes =
3611 resolvePrivateLocalDynamicExtents(privateLocal);
3613 unsigned dynIdx = 0;
3614 for (
auto innerDim : baseTy.getShape()) {
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]);
3625 subviewSizes.push_back(rewriter.
getIndexAttr(innerDim));
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)
3644 MemRefType viewType = MemRefType::get(viewShape, baseTy.getElementType());
3645 auto view = memref::ViewOp::create(rewriter, loc, viewType, memBuffer,
3646 c0.getResult(), viewDynSizes);
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);
3660 memref::ExtractStridedMetadataOp::create(rewriter, loc, subview);
3662 rewriter, loc, getElementSizeInBytes(loc, baseTy.getElementType()));
3664 arith::MulIOp::create(rewriter, loc, metadata.getOffset(), elementBytes);
3665 Value privateView = memref::ViewOp::create(rewriter, loc, baseTy, memBuffer,
3666 byteOffset, innerDynSizes);
3668 privateLocal.getType());
3669 mapping.
map(privateLocal.getResult(),
result);
3673template <
typename LoopOp>
3674void ACCCGToGPULowering::processSeqLoop(LoopOp loopOp) {
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());
3688 if (
auto copies = isEligibleForSharedMemory(privateLocal, baseTy)) {
3689 processPrivateLocal(privateLocal,
copies);
3690 preProcessedPrivateLocals.insert(privateLocal.getOperation());
3698 &newLoop.getRegion(), newLoop.getRegion().begin(),
3699 loopOp.getBody()->getArgumentTypes(),
3700 SmallVector<Location>(loopOp.getBody()->getArgumentTypes().size(),
3706 assert(blockArgs.size() &&
"expected block arguments for loop");
3707 mapping.
map(blockArgs, newLoop.getBody()->getArguments());
3713 if (needsInLoopReuseBarrier(loopOp.getOperation()) &&
3715 emitGPUBarrierWorkgroup(rewriter, loopOp->getLoc());
3717 for (
auto &bodyOp : loopOp.getBody()->getOperations()) {
3718 if (preProcessedPrivateLocals.contains(&bodyOp))
3723 mapping.
map(loopOp.getResults(), newLoop.getResults());
3728 if (hasTrailingSideEffectSiblings(loopOp.getOperation()))
3729 deferredBarrierSeqLoops.push_back(loopOp.getOperation());
3731 createBarrierAfterSeqLoop(loopOp.getOperation());
3734void ACCCGToGPULowering::flushDeferredBarriersBefore(Operation *beforeOp) {
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())
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);
3753 deferredBarrierSeqLoops.end());
3758void ACCCGToGPULowering::processParallelOp(scf::ParallelOp parallelOp) {
3759 LLVM_DEBUG(llvm::dbgs() <<
"processing par loop: ";
3760 parallelOp->print(llvm::dbgs()); llvm::dbgs() <<
"\n");
3762 "requires parallel dimensions attribute");
3763 mlir::acc::GPUParallelDimsAttr pDimsAttr =
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");
3772 mlir::acc::GPUParallelDimAttr parDim = pDimsAttr.getArray().front();
3774 bool savedGridStrideFlag = insideAccumulateGridStride;
3775 Value savedReductionBuf = reductionSharedBuf;
3776 if (parDim.isThreadX()) {
3778 parallelOp.getBody()->walk([&](acc::ReductionAccumulateOp accOp) {
3779 bool hasBlockDim =
false;
3780 bool hasThreadDim =
false;
3781 for (
auto d : accOp.getParDims().getArray()) {
3784 if (d.isThreadX() || d.isThreadY())
3785 hasThreadDim =
true;
3787 if (hasThreadDim && !hasBlockDim) {
3794 insideAccumulateGridStride =
true;
3798 auto processLoopBody = [&]() {
3800 for (
auto &bodyOp : parallelOp.getBody()->getOperations()) {
3801 if (bodyOp.hasTrait<OpTrait::IsTerminator>()) {
3803 flushDeferredBarriersBefore(&bodyOp);
3811 if (parDim.isSeq()) {
3812 LLVM_DEBUG(llvm::dbgs() <<
"loop: parDim: " << parDim <<
" as gpu seq\n");
3818 bool needsAtomicReduction =
false;
3819 bool hasAccumulateSibling =
false;
3820 if (scf::ParallelOp parentPar =
3821 parallelOp->getParentOfType<scf::ParallelOp>()) {
3822 if (mlir::acc::GPUParallelDimsAttr parentDims =
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()) {
3834 if (d.isThreadX() || d.isThreadY())
3835 hasThreadDim =
true;
3837 if (hasThreadDim && !hasBlockDim)
3838 hasAccumulateSibling =
true;
3843 if (insideAccumulateGridStride || hasAccumulateSibling) {
3844 for (
auto launchArg : computeRegion.getLaunchArgs()) {
3845 if (acc::ParWidthOp pw = launchArg.getDefiningOp<acc::ParWidthOp>()) {
3846 if (pw.getParDim().isThreadX()) {
3848 needsAtomicReduction = (*cval >=
options.subgroupSize);
3850 needsAtomicReduction =
true;
3856 if (needsAtomicReduction && !reductionSharedBuf) {
3858 parallelOp.getBody()->walk([&](acc::ReductionAccumulateOp accOp) {
3859 Type t = accOp.getValue().getType();
3860 if (isa<FloatType, IntegerType>(t))
3865 needsAtomicReduction =
false;
3867 if (needsAtomicReduction && !reductionSharedBuf) {
3868 Location seqLoc = parallelOp->getLoc();
3869 gpu::AddressSpaceAttr workgroupAS = gpu::AddressSpaceAttr::get(
3870 computeRegion->getContext(),
3871 gpu::GPUDialect::getWorkgroupAddressSpace());
3873 parallelOp.getBody()->
walk([&](acc::ReductionAccumulateOp accOp) {
3874 Type t = accOp.getValue().getType();
3875 if (isa<FloatType, IntegerType>(t))
3879 assert(elemTy &&
"expected scalar reduction element type");
3881 MemRefType bufTy = MemRefType::get({
options.subgroupSize}, elemTy,
3882 AffineMap{}, workgroupAS);
3883 reductionSharedBuf = acc::GPUSharedMemoryOp::create(
3887 Value tidY = getThreadId(seqLoc, gpu::Dimension::y);
3889 if (isa<FloatType>(elemTy)) {
3890 identity = arith::ConstantOp::create(
3891 rewriter, seqLoc, elemTy, rewriter.
getFloatAttr(elemTy, 0.0));
3895 memref::StoreOp::create(rewriter, seqLoc, identity, reductionSharedBuf,
3897 createPerRowBarrier(seqLoc);
3899 processSeqLoop(parallelOp);
3900 loopReductions.push_back(parallelOp);
3902 LLVM_DEBUG(llvm::dbgs()
3903 <<
"processing loop: parDim: " << parDim <<
" as gpu par\n");
3907 Value gpuThreadId = getGPUThreadIdFor(parDim.getProcessor());
3908 mapping.
map(parallelOp.getInductionVars()[0], gpuThreadId);
3916 if (needsBarrierAfterThreadLoop(parallelOp))
3917 createBarrier(parallelOp->getLoc(), pDimsAttr);
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(),
3927 mapping.map(v, zero);
3929 loopReductions.push_back(parallelOp);
3931 insideAccumulateGridStride = savedGridStrideFlag;
3932 if (!insideAccumulateGridStride && !savedReductionBuf)
3933 reductionSharedBuf = Value();
3937static gpu::AllReduceOperation
3938getAllReduceOperation(arith::AtomicRMWKind 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:
3971 llvm_unreachable(
"unsupported atomic kind");
3974void ACCCGToGPULowering::constructAtomicAccumulation(
3976 arith::AtomicRMWKind kind) {
3978 "cannot lower atomic accumulation on an stack variable");
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,
4000 auto atomicUpdateOp =
4001 acc::AtomicUpdateOp::create(rewriter, loc,
target, Value());
4002 Region ®ion = atomicUpdateOp->getRegion(0);
4006 Value reductionExpr =
4008 acc::YieldOp::create(rewriter, loc, reductionExpr);
4012void ACCCGToGPULowering::createGPUAllReduceOp(
4013 Location loc, Value input, Value memref, arith::AtomicRMWKind kind,
4015 bool isPerThreadPrivateTarget) {
4016 gpu::AllReduceOperationAttr attr = gpu::AllReduceOperationAttr::get(
4017 computeRegion->getContext(), getAllReduceOperation(kind));
4018 auto emitAllReduce = [&](Value operand) -> Value {
4020 gpu::AllReduceOp::create(rewriter, loc, operand, attr,
true);
4026 if (
auto complexType = dyn_cast<ComplexType>(input.
getType())) {
4031 if (kind != arith::AtomicRMWKind::addf) {
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());
4040 Type elementType = complexType.getElementType();
4042 emitAllReduce(complex::ReOp::create(rewriter, loc, elementType, input));
4044 emitAllReduce(complex::ImOp::create(rewriter, loc, elementType, input));
4045 reducedValue = complex::CreateOp::create(rewriter, loc, complexType,
4046 realResult, imagResult);
4048 reducedValue = emitAllReduce(input);
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())
4062 if (parDim.isThreadX())
4064 if (computeRegion.getLaunchArg(parDim) ||
4066 inactiveParDims.push_back(parDim);
4072 if (!hasThreadX && !isSingleThreadWorkerLaunch())
4073 inactiveParDims.push_back(mlir::acc::GPUParallelDimAttr::threadXDim(ctx));
4074 Value predicate = emitPredicate(loc, inactiveParDims);
4081 bool isPerThreadPrivate = isPerThreadPrivateTarget ||
4082 isa_and_nonnull<memref::AllocaOp>(
4083 unwrapMemRefConversion(memref).getDefiningOp());
4086 if (predicate && !isPerThreadPrivate) {
4088 scf::IfOp::create(rewriter, loc, predicate,
false);
4089 Region &thenRegion = ifOp.getThenRegion();
4093 memref::StoreOp::create(rewriter, loc, reducedValue, memref,
indices);
4094 if (predicate && !isPerThreadPrivate)
4099 reductionAccumValue[memref] = reducedValue;
4102void ACCCGToGPULowering::postprocessAccumulateOp(
4103 acc::ReductionAccumulateOp op) {
4104 Location loc = op->getLoc();
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);
4121 std::optional<arith::AtomicRMWKind> kind;
4123 FailureOr<arith::AtomicRMWKind> kindOr = getReductionKind(
4124 op.getReductionOperator(), op.getValue().getType(), loc);
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,
4138 createPerRowBarrier(loc);
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,
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()));
4167 Value predicate = emitPredicate(loc, predDims);
4169 scf::IfOp::create(rewriter, loc, predicate,
false);
4171 memref::StoreOp::create(rewriter, loc, val, mem);
4174 memref::StoreOp::create(rewriter, loc, val, mem);
4182void ACCCGToGPULowering::postprocessLoopReduction(scf::ParallelOp parLoop) {
4183 if (parLoop.getNumReductions() == 0)
4186 for (
unsigned i = 0; i < parLoop.getNumResults(); ++i) {
4187 for (Operation *user :
4189 if (acc::ReductionAccumulateOp accumulateOp =
4190 dyn_cast<acc::ReductionAccumulateOp>(user)) {
4191 postprocessAccumulateOp(accumulateOp);
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();
4204 auto executeRegionOp = scf::ExecuteRegionOp::create(rewriter, loc, types);
4205 Region ®ion = executeRegionOp.getRegion();
4209 llvm::DenseMap<Block *, Block *> blockMap;
4210 blockMap[&oldRegion.
front()] = ®ion.
front();
4214 for (
auto &oldBlock : llvm::drop_begin(oldRegion.
getBlocks())) {
4215 TypeRange argTypes = oldBlock.getArgumentTypes();
4216 size_t numArgs = argTypes.size();
4219 SmallVector<Location>(numArgs, loc));
4220 blockMap[&oldBlock] = newBlock;
4227 for (
auto [oldBlock, newBlock] :
4229 OpBuilder::InsertionGuard blockGuard(rewriter);
4231 for (
auto &bodyOp : oldBlock.getOperations()) {
4233 if (bodyOp.hasTrait<OpTrait::IsTerminator>())
4239 Operation *oldTerminator = oldBlock.getTerminator();
4241 Operation *newTerminator = rewriter.
clone(*oldTerminator, mapping);
4246 Block *newDest = blockMap.lookup(oldDest);
4247 assert(newDest &&
"Successor block must be in blockMap");
4251 mapping.
map(op->getResults(), executeRegionOp->getResults());
4255void ACCCGToGPULowering::processAccumulateOp(acc::ReductionAccumulateOp op) {
4256 LLVM_DEBUG(llvm::dbgs() <<
"processing accumulate op: " << *op <<
"\n");
4257 Value accumulateValue = op.getValue();
4258 if (reductionSharedBuf &&
4260 cast<MemRefType>(reductionSharedBuf.getType()).getElementType()) {
4261 Location loc = op->getLoc();
4262 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
4263 op.getReductionOperator(), accumulateValue.
getType(), loc);
4268 Value tidY = getThreadId(loc, gpu::Dimension::y);
4269 memref::AtomicRMWOp::create(rewriter, loc, *kind, mappedValue,
4271 createPerRowBarrier(loc);
4273 memref::LoadOp::create(rewriter, loc, reductionSharedBuf, tidY);
4274 memref::StoreOp::create(rewriter, loc,
result, memref);
4275 reductionAccumValue[memref] =
result;
4279 Operation *newOp = rewriter.
clone(*op, mapping);
4281 }
else if (isRedundantChainAccumulate(op)) {
4287 LLVM_DEBUG(llvm::dbgs() <<
" skipped: redundant chain accumulate\n");
4288 gpu::BarrierOp::create(rewriter, op->getLoc());
4292 FailureOr<arith::AtomicRMWKind> kind = getReductionKind(
4293 op.getReductionOperator(), accumulateValue.
getType(), op.getLoc());
4296 createGPUAllReduceOp(op->getLoc(), mappedValue, memref, *kind,
4305static bool isThreadVarying(Value v, ArrayRef<Value> threadIds,
4307 if (!v || !visited.insert(v).second)
4309 if (llvm::is_contained(threadIds, v))
4311 if (
auto arg = dyn_cast<BlockArgument>(v)) {
4313 unsigned dim = arg.getArgNumber();
4314 if (
auto loop = dyn_cast<scf::ParallelOp>(owner)) {
4315 if (dim >= loop.getLowerBound().size())
4317 return isThreadVarying(loop.getLowerBound()[dim], threadIds, visited) ||
4318 isThreadVarying(loop.getStep()[dim], threadIds, visited);
4320 if (
auto loop = dyn_cast<scf::ForOp>(owner))
4322 (isThreadVarying(loop.getLowerBound(), threadIds, visited) ||
4323 isThreadVarying(loop.getStep(), threadIds, visited));
4329 if (isa<gpu::ThreadIdOp, gpu::LaneIdOp>(def))
4331 return llvm::any_of(def->
getOperands(), [&](Value o) {
4332 return isThreadVarying(o, threadIds, visited);
4337static Value accumulatorRoot(Value v) {
4339 if (
auto cast = dyn_cast<memref::MemorySpaceCastOp>(op)) {
4340 v = cast.getSource();
4343 if (
auto viewLike = dyn_cast<ViewLikeOpInterface>(op)) {
4344 if (isa<MemRefType>(viewLike.getViewSource().getType())) {
4345 v = viewLike.getViewSource();
4356static Value matchAccumulatorUpdate(memref::StoreOp store, Value accum) {
4357 if (accumulatorRoot(store.getMemRef()) != accum)
4359 Operation *
combine = store.getValueToStore().getDefiningOp();
4360 if (!combine ||
combine->getNumOperands() != 2)
4362 for (
unsigned i = 0; i != 2; ++i) {
4363 auto load =
combine->getOperand(i).getDefiningOp<memref::LoadOp>();
4364 if (!
load || accumulatorRoot(
load.getMemRef()) != accum)
4366 if (!llvm::equal(
load.getIndices(), store.getIndices()))
4368 return combine->getOperand(1 - i);
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};
4384 while (!worklist.empty()) {
4385 Value cur = worklist.pop_back_val();
4386 if (!seen.insert(cur).second)
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());
4396 for (memref::StoreOp store : stores) {
4397 Value contribution = matchAccumulatorUpdate(store, accum);
4402 if (llvm::any_of(store.getIndices(), [&](Value idx) {
4403 DenseSet<Value> visited;
4404 return isThreadVarying(idx, threadIds, visited);
4407 Operation *
combine = store.getValueToStore().getDefiningOp();
4409 memref::AtomicRMWOp::create(rewriter, store.getLoc(), kind, contribution,
4410 store.getMemRef(), store.getIndices());
4412 if (combine &&
combine->use_empty())
4417void ACCCGToGPULowering::processAccumulateArrayOp(
4418 acc::ReductionAccumulateArrayOp op) {
4419 LLVM_DEBUG(llvm::dbgs() <<
"processing accumulate array op: " << *op <<
"\n");
4420 Location loc = op.getLoc();
4423 MemRefType memrefTy = dyn_cast<MemRefType>(memref.
getType());
4425 (void)accSupport.
emitNYI(loc,
"reduction: non-MemRefTy accumulate array");
4428 FailureOr<arith::AtomicRMWKind> kindOr = getReductionKind(
4429 op.getReductionOperator(), memrefTy.getElementType(), loc);
4432 arith::AtomicRMWKind kind = *kindOr;
4437 .getDefiningOp<acc::DataBoundsOp>();
4438 assert(boundsOp &&
"expected acc.bounds defining op for array accumulate");
4439 auto eraseDeadBounds = [&] {
4440 if (boundsOp->use_empty())
4444 auto isUnitExtent = [&](mlir::acc::GPUParallelDimAttr parDim) {
4445 std::optional<uint64_t> width =
4446 computeRegion.getKnownConstantLaunchArg(parDim);
4447 return width && *width == 1;
4451 bool hasThreadDim =
false;
4452 for (
auto pd : op.getParDims().getArray()) {
4453 if (isUnitExtent(pd))
4455 hasThreadDim |= pd.isAnyThread();
4461 if (!hasThreadDim) {
4474 auto storageIsThreadXPrivate = [&](Value v) ->
bool {
4475 acc::PrivateLocalOp privateLocal = getPrivateLocalForMemref(v);
4476 GPUParallelDimsAttr dims =
4477 privateLocal ? getPrivateParDims(privateLocal, computeRegion)
4478 : GPUParallelDimsAttr();
4480 if (Operation *root = unwrapMemRefConversion(v).getDefiningOp())
4484 llvm::any_of(dims.getArray(), [](
auto d) { return d.isThreadX(); });
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())) {
4492 addrSpace.getValue() == gpu::GPUDialect::getWorkgroupAddressSpace();
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();
4502 if (!isPerThreadPrivate) {
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,
4521 auto toIndex = [&](Value v) -> Value {
4524 return arith::IndexCastOp::create(rewriter, loc, rewriter.
getIndexType(),
4531 boundsOp.getLowerbound() ? toIndex(boundsOp.getLowerbound()) : zero;
4532 Value step = boundsOp.getStride() ? toIndex(boundsOp.getStride()) : one;
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);
4542 assert(boundsOp.getUpperbound() &&
4543 "acc.bounds must specify an extent or upperbound");
4544 ub = arith::AddIOp::create(rewriter, loc, toIndex(boundsOp.getUpperbound()),
4549 auto forOp = scf::ForOp::create(rewriter, loc, lb, ub, step);
4551 OpBuilder::InsertionGuard guard(rewriter);
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) {
4560 memrefTy.isDynamicDim(dim)
4561 ? memref::DimOp::create(rewriter, loc, memref, dim).getResult()
4563 memrefTy.getDimSize(dim))
4566 arith::RemUIOp::create(rewriter, loc, linearIndex, dimSize);
4569 arith::DivUIOp::create(rewriter, loc, linearIndex, dimSize);
4572 Value elem = memref::LoadOp::create(rewriter, loc, memref,
indices);
4573 createGPUAllReduceOp(loc, elem, memref, kind, op.getParDims(),
indices,
4580void ACCCGToGPULowering::processReductionOp(acc::ReductionInitOp op) {
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)));
4587 if (innerOp->getNumRegions() > 0) {
4591 rewriter.
clone(*innerOp, mapping);
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);
4609 arith::AtomicRMWKind kind = *kindOr;
4620 bool destIsPerThreadPrivate = isa_and_nonnull<memref::AllocaOp>(
4621 unwrapMemRefConversion(destMemref).getDefiningOp());
4623 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
4629 bool destIsGridShared =
4630 !destIsPerThreadPrivate &&
4631 (llvm::any_of(parDims,
4632 [](mlir::acc::GPUParallelDimAttr parDim) {
4633 return parDim.isAnyBlock();
4635 computeRegion.launchesMultipleBlocks());
4636 if (destIsGridShared) {
4642 memref::LoadOp::create(rewriter, loc, srcMemref,
ValueRange{});
4643 pendingCombineReloads.push_back({srcMemref, srcLoad});
4644 constructAtomicAccumulation(loc, destMemref, {}, srcLoad, kind);
4650 auto srcLoad = memref::LoadOp::create(rewriter, loc, srcMemref,
ValueRange{});
4652 memref::LoadOp::create(rewriter, loc, destMemref,
ValueRange{});
4654 memref::StoreOp::create(rewriter, loc, combine, destMemref,
ValueRange{});
4657void ACCCGToGPULowering::processCombineRegionOp(
4658 acc::ReductionCombineRegionOp op) {
4659 LLVM_DEBUG(llvm::dbgs() <<
"processing combine region op: ";
4660 op->print(llvm::dbgs()); llvm::dbgs() <<
"\n");
4664 bool destIsPerThreadPrivate = isa_and_nonnull<memref::AllocaOp>(
4667 SmallVector<mlir::acc::GPUParallelDimAttr> parDims =
4669 for (
auto parDim : parDims) {
4670 if (parDim.isAnyBlock() && !destIsPerThreadPrivate) {
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);
4685 auto reductionLoad =
4686 memref::LoadOp::create(rewriter, loc, srcMemref,
ValueRange{});
4687 pendingCombineReloads.push_back({srcMemref, reductionLoad});
4688 constructAtomicAccumulation(loc,
4690 {}, reductionLoad, *kind);
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;
4708 constructAtomicAccumulation(loc,
4710 {}, reductionResult, kind);
4715 op.getRegion().walk<WalkOrder::PreOrder>([&](Operation *innerOp) {
4716 if (acc::YieldOp yieldOp = dyn_cast<acc::YieldOp>(innerOp))
4718 if (innerOp->getNumRegions() > 0) {
4722 rewriter.
clone(*innerOp, mapping);
4727void ACCCGToGPULowering::processGenericOp(Operation *op) {
4730 LLVM_DEBUG(llvm::dbgs() <<
"processing generic op, cloning: ";
4731 op->
print(llvm::dbgs()); llvm::dbgs() <<
"\n");
4732 Operation *newOp = rewriter.
clone(*op, mapping);
4737void ACCCGToGPULowering::processGenericOpWithRegions(Operation *op) {
4739 LLVM_DEBUG(llvm::dbgs() <<
"processing generic op with regions: ";
4740 op->
print(llvm::dbgs()); llvm::dbgs() <<
"\n");
4746 for (
auto [oldRegion, newRegion] :
4747 llvm::zip(op->
getRegions(), newOp->getRegions())) {
4749 for (
auto &oldBlock : oldRegion.
getBlocks()) {
4750 TypeRange argTypes = oldBlock.getArgumentTypes();
4751 size_t numArgs = argTypes.size();
4754 rewriter.
createBlock(&newRegion, newRegion.end(), argTypes,
4755 SmallVector<Location>(numArgs, op->
getLoc()));
4761 for (
auto &innerOp : oldBlock.getOperations()) {
4762 OpBuilder::InsertionGuard guard(rewriter);
4764 processOp(&innerOp);
4775void ACCCGToGPULowering::processOp(Operation *op) {
4776 if (isDeferredBarrierFlushPoint(op))
4777 flushDeferredBarriersBefore(op);
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());
4812 LLVM_DEBUG(llvm::dbgs() <<
"skipping mapped op: " << *op <<
"\n");
4813 }
else if (isa<acc::YieldOp>(op)) {
4814 for (
auto [operand,
result] :
4818 }
else if (isa<scf::ExecuteRegionOp>(op)) {
4819 processExecuteRegion(cast<scf::ExecuteRegionOp>(op));
4821 isa<acc::OpenACCDialect>(op->
getDialect())) {
4822 processGenericOp(op);
4824 processGenericOpWithRegions(op);
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()) {
4844class ACCComputeRegionToGPUPattern
4845 :
public OpRewritePattern<acc::ComputeRegionOp> {
4847 ACCComputeRegionToGPUPattern(MLIRContext *context,
4848 acc::OpenACCSupport &accSupport,
4849 const ACCCGToGPUOptions &
options)
4850 : OpRewritePattern<acc::ComputeRegionOp>(context), accSupport(accSupport),
4853 LogicalResult matchAndRewrite(acc::ComputeRegionOp op,
4854 PatternRewriter &rewriter)
const override {
4855 ACCCGToGPULowering kernelOpRewriter(op, rewriter, accSupport,
options);
4856 return kernelOpRewriter.rewrite();
4860 acc::OpenACCSupport &accSupport;
4861 const ACCCGToGPUOptions &
options;
4864class ACCCGToGPU :
public acc::impl::ACCCGToGPUBase<ACCCGToGPU> {
4866 using acc::impl::ACCCGToGPUBase<ACCCGToGPU>::ACCCGToGPUBase;
4868 void getDependentDialects(DialectRegistry ®istry)
const override {
4873 void runOnOperation()
override {
4874 FunctionOpInterface funcOp = getOperation();
4875 MLIRContext *context = funcOp->getContext();
4877 assert(deviceType != mlir::acc::DeviceType::Host &&
4878 deviceType != mlir::acc::DeviceType::Multicore &&
4879 "ACCCGToGPU only supports GPU device types");
4883 WalkResult
result = funcOp->walk([](scf::ParallelOp loop) {
4884 if (!loop->getParentOfType<acc::ComputeRegionOp>() ||
4887 loop.emitOpError(
"requires an 'acc.par_dims' attribute");
4890 if (
result.wasInterrupted()) {
4891 signalPassFailure();
4896 options.deviceType = deviceType;
4897 options.maxWorkgroupSharedMemory = maxWorkgroupSharedMemory;
4898 options.maxThreadPrivateStack = maxThreadPrivateStack;
4899 options.subgroupSize = subgroupSize;
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>();
4908 RewritePatternSet patterns(context);
4909 patterns.insert<ACCComputeRegionToGPUPattern>(context, accSupport,
options);
4910 patterns.insert<RemoveParWidth>(context);
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();
static void createForAllDimensions(OpBuilder &builder, Location loc, SmallVectorImpl< Value > &values)
*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...
static llvm::ManagedStatic< PassManagerOptions > options
static void rewrite(DataFlowSolver &solver, MLIRContext *context, MutableArrayRef< Region > initialRegions)
Rewrite the given regions using the computing analysis.
Block represents an ordered list of Operations.
MutableArrayRef< BlockArgument > BlockArgListType
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
RetT walk(FnT &&callback)
Walk all nested operations, blocks (including this block) or regions, depending on the type of callba...
Operation * getTerminator()
Get the terminator operation of this block.
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
BlockArgListType getArguments()
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getI32IntegerAttr(int32_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getFloatAttr(Type type, double value)
IntegerAttr getI64IntegerAttr(int64_t value)
TypedAttr getZeroAttr(Type type)
MLIRContext * getContext() const
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
auto lookup(T from) const
Lookup a mapped value within the map.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
bool contains(T from) const
Checks to see if a mapping for 'from' exists.
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
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.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Operation is the basic unit of execution within MLIR.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Value getOperand(unsigned idx)
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
unsigned getNumSuccessors()
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
result_iterator result_begin()
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
void print(raw_ostream &os, const OpPrintingFlags &flags={})
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
result_iterator result_end()
operand_range getOperands()
Returns an iterator on the underlying Value's.
void setSuccessor(Block *block, unsigned index)
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
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),...
Block * getSuccessor(unsigned index)
result_range getResults()
MLIRContext * getContext()
Return the context this operation is associated with.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
BlockListType & getBlocks()
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...
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...
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
auto walk(WalkFns &&...walkFns)
Walk this type and all attibutes/types nested within using the provided walk functions.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
user_iterator user_begin() const
user_range getUsers() const
bool hasOneUse() const
Returns true if this value has exactly one use.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static WalkResult advance()
static WalkResult interrupt()
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 ®istry) 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.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Specialization of arith.constant op that returns an integer value.
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
static ConcreteType get(MLIRContext *ctx, Args &&...args)
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()
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.
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()
Value castPointerLikeTypeIfNeeded(OpBuilder &builder, Location loc, Value value, Type resultType)
Cast value to resultType via PointerLikeType::genCast when needed.
int64_t sumExistingSharedMemoryBytes(Region ®ion)
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 ®istry)
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.
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.
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.
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...
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
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.
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.