[Openmp-commits] [flang] [mlir] [openmp] [Flang][OpenMP] Lower scan directive and inscan reduction modifier (PR #206747)
CHANDRA GHALE via Openmp-commits
openmp-commits at lists.llvm.org
Wed Jul 1 00:44:34 PDT 2026
https://github.com/chandraghale updated https://github.com/llvm/llvm-project/pull/206747
>From 82416bc775c4befdbcce1f999a5f5b97ef954cd8 Mon Sep 17 00:00:00 2001
From: Chandra Ghale <ghale at pe34genoa.hpc.amslabs.hpecorp.net>
Date: Tue, 30 Jun 2026 10:00:56 -0500
Subject: [PATCH 1/2] Lower scan directive and inscan reduction modifier
---
flang/lib/Lower/OpenMP/OpenMP.cpp | 57 ++-
.../Lower/OpenMP/Todo/nested-wsloop-scan.f90 | 34 ++
.../OpenMP/Todo/wsloop-scan-collapse.f90 | 29 ++
.../OpenMP/OpenMPToLLVMIRTranslation.cpp | 476 +++++++++++++++---
.../Target/LLVMIR/openmp-reduction-scan.mlir | 123 +++++
mlir/test/Target/LLVMIR/openmp-todo.mlir | 41 +-
openmp/runtime/test/scan/scan.f90 | 38 ++
7 files changed, 726 insertions(+), 72 deletions(-)
create mode 100644 flang/test/Lower/OpenMP/Todo/nested-wsloop-scan.f90
create mode 100644 flang/test/Lower/OpenMP/Todo/wsloop-scan-collapse.f90
create mode 100644 mlir/test/Target/LLVMIR/openmp-reduction-scan.mlir
create mode 100644 openmp/runtime/test/scan/scan.f90
diff --git a/flang/lib/Lower/OpenMP/OpenMP.cpp b/flang/lib/Lower/OpenMP/OpenMP.cpp
index ea8c279962508..e77584a142eea 100644
--- a/flang/lib/Lower/OpenMP/OpenMP.cpp
+++ b/flang/lib/Lower/OpenMP/OpenMP.cpp
@@ -2972,12 +2972,59 @@ genParallelOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
static mlir::omp::ScanOp
genScanOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
- semantics::SemanticsContext &semaCtx, mlir::Location loc,
- const ConstructQueue &queue, ConstructQueue::const_iterator item) {
+ semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
+ mlir::Location loc, const ConstructQueue &queue,
+ ConstructQueue::const_iterator item) {
mlir::omp::ScanOperands clauseOps;
genScanClauses(converter, semaCtx, item->clauses, loc, clauseOps);
- return mlir::omp::ScanOp::create(converter.getFirOpBuilder(),
- converter.getCurrentLocation(), clauseOps);
+ mlir::omp::ScanOp scanOp = mlir::omp::ScanOp::create(
+ converter.getFirOpBuilder(), converter.getCurrentLocation(), clauseOps);
+
+ /// Scan reduction is not implemented with nested workshare loops, linear
+ /// clause, tiling
+ mlir::omp::LoopNestOp loopNestOp =
+ scanOp->getParentOfType<mlir::omp::LoopNestOp>();
+ llvm::SmallVector<mlir::omp::LoopWrapperInterface> loopWrappers;
+ loopNestOp.gatherWrappers(loopWrappers);
+ mlir::Operation *loopWrapperOp = loopWrappers.front().getOperation();
+ if (llvm::isa<mlir::omp::SimdOp>(loopWrapperOp))
+ TODO(loc, "unsupported simd");
+ if (loopWrappers.size() > 1)
+ TODO(loc, "unsupported composite");
+ mlir::omp::WsloopOp wsLoopOp = llvm::cast<mlir::omp::WsloopOp>(loopWrapperOp);
+ bool isNested =
+ (loopNestOp.getNumLoops() > 1) ||
+ (wsLoopOp && (wsLoopOp->getParentOfType<mlir::omp::WsloopOp>()));
+ if (isNested)
+ TODO(loc, "Scan directive inside nested workshare loops");
+ if (wsLoopOp && !wsLoopOp.getLinearVars().empty())
+ TODO(loc, "Scan directive with linear clause");
+ if (loopNestOp.getTileSizes())
+ TODO(loc, "Scan directive with loop tiling");
+
+ // All loop indices should be loaded after the scan construct as otherwise,
+ // it would result in using the index variable across scan directive.
+ // (`Intra-iteration dependences from a statement in the structured
+ // block sequence that precede a scan directive to a statement in the
+ // structured block sequence that follows a scan directive must not exist,
+ // except for dependences for the list items specified in an inclusive or
+ // exclusive clause.`).
+ // TODO: Nested loops are not handled.
+ mlir::Region ®ion = loopNestOp->getRegion(0);
+ mlir::Value indexVal = fir::getBase(region.getArgument(0));
+ lower::pft::Evaluation *doConstructEval = eval.parentConstruct;
+ fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+ lower::pft::Evaluation *doLoop = &doConstructEval->getFirstNestedEvaluation();
+ auto *doStmt = doLoop->getIf<parser::NonLabelDoStmt>();
+ assert(doStmt && "Expected do loop to be in the nested evaluation");
+ const auto &loopControl =
+ std::get<std::optional<parser::LoopControl>>(doStmt->t);
+ const parser::LoopControl::Bounds *bounds =
+ std::get_if<parser::LoopControl::Bounds>(&loopControl->u);
+ mlir::Operation *storeOp =
+ setLoopVar(converter, loc, indexVal, bounds->Name().thing.symbol);
+ firOpBuilder.setInsertionPointAfter(storeOp);
+ return scanOp;
}
static mlir::omp::SectionsOp
@@ -4305,7 +4352,7 @@ static void genOMPDispatch(lower::AbstractConverter &converter,
loc, queue, item);
break;
case llvm::omp::Directive::OMPD_scan:
- newOp = genScanOp(converter, symTable, semaCtx, loc, queue, item);
+ newOp = genScanOp(converter, symTable, semaCtx, eval, loc, queue, item);
break;
case llvm::omp::Directive::OMPD_section:
llvm_unreachable("genOMPDispatch: OMPD_section");
diff --git a/flang/test/Lower/OpenMP/Todo/nested-wsloop-scan.f90 b/flang/test/Lower/OpenMP/Todo/nested-wsloop-scan.f90
new file mode 100644
index 0000000000000..414e2ef2d5aed
--- /dev/null
+++ b/flang/test/Lower/OpenMP/Todo/nested-wsloop-scan.f90
@@ -0,0 +1,34 @@
+! Tests scan reduction behavior when used in nested workshare loops
+
+! RUN: %not_todo_cmd %flang_fc1 -emit-hlfir -fopenmp -o - %s 2>&1 | FileCheck %s
+
+program nested_scan_example
+ implicit none
+ integer, parameter :: n = 4, m = 5
+ integer :: a(n, m), b(n, m)
+ integer :: i, j
+ integer :: row_sum, col_sum
+
+ do i = 1, n
+ do j = 1, m
+ a(i, j) = i + j
+ end do
+ end do
+
+ !$omp parallel do reduction(inscan, +: row_sum) private(col_sum, j)
+ do i = 1, n
+ row_sum = row_sum + i
+ !$omp scan inclusive(row_sum)
+
+ col_sum = 0
+ !$omp parallel do reduction(inscan, +: col_sum)
+ do j = 1, m
+ col_sum = col_sum + a(i, j)
+ !CHECK: not yet implemented: Scan directive inside nested workshare loops
+ !$omp scan inclusive(col_sum)
+ b(i, j) = col_sum + row_sum
+ end do
+ !$omp end parallel do
+ end do
+ !$omp end parallel do
+end program nested_scan_example
diff --git a/flang/test/Lower/OpenMP/Todo/wsloop-scan-collapse.f90 b/flang/test/Lower/OpenMP/Todo/wsloop-scan-collapse.f90
new file mode 100644
index 0000000000000..b8e6e831884ab
--- /dev/null
+++ b/flang/test/Lower/OpenMP/Todo/wsloop-scan-collapse.f90
@@ -0,0 +1,29 @@
+! Tests scan reduction behavior when used in nested workshare loops
+
+! RUN: %not_todo_cmd %flang_fc1 -emit-hlfir -fopenmp -o - %s 2>&1 | FileCheck %s
+
+program nested_loop_example
+ implicit none
+ integer :: i, j, x
+ integer, parameter :: N = 100, M = 200
+ real :: A(N, M), B(N, M)
+ x = 0
+
+ do i = 1, N
+ do j = 1, M
+ A(i, j) = i * j
+ end do
+ end do
+
+ !$omp parallel do collapse(2) reduction(inscan, +:x)
+ do i = 1, N
+ do j = 1, M
+ x = x + A(i,j)
+ !CHECK: not yet implemented: Scan directive inside nested workshare loops
+ !$omp scan inclusive(x)
+ B(i, j) = x
+ end do
+ end do
+ !$omp end parallel do
+
+end program nested_loop_example
diff --git a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index d860c408e0fd2..297ebac51de88 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -41,6 +41,8 @@
#include "llvm/TargetParser/Triple.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
+#include <cassert>
+#include <cstddef>
#include <cstdint>
#include <iterator>
#include <numeric>
@@ -84,6 +86,10 @@ class OpenMPAllocStackFrame
: allocInsertPoint(allocaIP), deallocBlocks(deallocBlocks) {}
llvm::OpenMPIRBuilder::InsertPointTy allocInsertPoint;
llvm::SmallVector<llvm::BasicBlock *> deallocBlocks;
+ /// Set to true when this alloca frame encloses an omp.parallel operation.
+ /// The alloca insertion point of a function in which a parallel op is
+ /// defined may be used to allocate the temporary buffer for scan reductions.
+ bool containsParallelOp = false;
};
/// Stack frame to hold a \see llvm::CanonicalLoopInfo representing the
@@ -93,7 +99,17 @@ class OpenMPLoopInfoStackFrame
: public StateStackFrameBase<OpenMPLoopInfoStackFrame> {
public:
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OpenMPLoopInfoStackFrame)
+ /// For constructs like `scan`, a single `omp.loop_nest` is split into an
+ /// input loop and a scan loop. In that case `loopInfo` holds the input loop
+ /// info and `scanloopInfo` holds the scan loop info.
llvm::CanonicalLoopInfo *loopInfo = nullptr;
+ llvm::CanonicalLoopInfo *scanloopInfo = nullptr;
+ llvm::ScanInfo *scanInfo = nullptr;
+ /// Map reduction variables to their LLVM types. Populated when the reduction
+ /// clause is processed and used when a `scan` directive is encountered in the
+ /// loop body.
+ std::unique_ptr<llvm::DenseMap<llvm::Value *, llvm::Type *>>
+ reductionVarToType = nullptr;
};
/// Custom error class to signal translation errors that don't need reporting,
@@ -359,6 +375,10 @@ static LogicalResult checkImplementationStatus(Operation &op) {
if (!op.getDependVars().empty() || op.getDependKinds())
result = todo("depend");
};
+ auto checkExclusive = [&todo](auto op, LogicalResult &result) {
+ if (!op.getExclusiveVars().empty())
+ result = todo("exclusive");
+ };
auto checkHint = [](auto op, LogicalResult &) {
if (op.getHint())
op.emitWarning("hint clause discarded");
@@ -389,21 +409,27 @@ static LogicalResult checkImplementationStatus(Operation &op) {
op.getReductionMod().value() != omp::ReductionModifier::defaultmod) {
omp::ReductionModifier mod = op.getReductionMod().value();
// The `task` reduction modifier is supported on the parallel and
- // worksharing (do/for and sections) constructs. Other modifiers, and the
- // `task` modifier on other constructs, are not yet implemented.
+ // worksharing (do/for and sections) constructs. The `inscan` modifier is
+ // supported on the worksharing-loop construct (it is translated as a scan
+ // reduction). Other modifiers, and these modifiers on other constructs,
+ // are not yet implemented.
bool taskModifierSupported =
mod == omp::ReductionModifier::task &&
isa<omp::ParallelOp, omp::WsloopOp, omp::SectionsOp>(op);
- if (!taskModifierSupported) {
+ bool inscanModifierSupported =
+ mod == omp::ReductionModifier::inscan && isa<omp::WsloopOp>(op);
+ if (!taskModifierSupported && !inscanModifierSupported) {
result = todo("reduction with modifier");
- } else if (auto byref = op.getReductionByref()) {
- // The task reduction modifier lowering only handles non-byref
- // reductions for now.
- for (bool isByRef : *byref)
- if (isByRef) {
- result = todo("task reduction modifier with by-ref reduction");
- break;
- }
+ } else if (taskModifierSupported) {
+ if (auto byref = op.getReductionByref()) {
+ // The task reduction modifier lowering only handles non-byref
+ // reductions for now.
+ for (bool isByRef : *byref)
+ if (isByRef) {
+ result = todo("task reduction modifier with by-ref reduction");
+ break;
+ }
+ }
}
}
};
@@ -460,6 +486,7 @@ static LogicalResult checkImplementationStatus(Operation &op) {
checkAllocate(op, result);
checkOrder(op, result);
})
+ .Case([&](omp::ScanOp op) { checkExclusive(op, result); })
.Case([&](omp::SectionsOp op) {
checkAllocate(op, result);
checkPrivate(op, result);
@@ -650,6 +677,97 @@ findCurrentLoopInfo(LLVM::ModuleTranslation &moduleTranslation) {
return loopInfo;
}
+/// Find the scan loop information structure for the scan loop nest being
+/// translated. It will return a `null` value unless called from the
+/// translation function for a loop wrapper operation after successfully
+/// translating its body.
+static llvm::CanonicalLoopInfo *
+findCurrentScanLoopInfo(LLVM::ModuleTranslation &moduleTranslation) {
+ llvm::CanonicalLoopInfo *scanLoopInfo = nullptr;
+ moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
+ [&](OpenMPLoopInfoStackFrame &frame) {
+ scanLoopInfo = frame.scanloopInfo;
+ return WalkResult::interrupt();
+ });
+ return scanLoopInfo;
+}
+
+/// Find the `ScanInfo` stored on the loop stack frame. Upon encountering an
+/// `inscan` reduction modifier, `scanInfoInitialize` initializes the
+/// `ScanInfo`, which is then used when a `scan` directive is encountered in the
+/// body of the loop nest.
+static llvm::ScanInfo *
+findScanInfo(LLVM::ModuleTranslation &moduleTranslation) {
+ llvm::ScanInfo *scanInfo = nullptr;
+ moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
+ [&](OpenMPLoopInfoStackFrame &frame) {
+ scanInfo = frame.scanInfo;
+ return WalkResult::interrupt();
+ });
+ return scanInfo;
+}
+
+/// The types of reduction variables are used for lowering a `scan` directive
+/// that appears in the body of the loop. The types are stored in the loop frame
+/// when the reduction clause is encountered and used when the `scan` directive
+/// is encountered.
+static llvm::DenseMap<llvm::Value *, llvm::Type *> *
+findReductionVarTypes(LLVM::ModuleTranslation &moduleTranslation) {
+ llvm::DenseMap<llvm::Value *, llvm::Type *> *reductionVarToType = nullptr;
+ moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
+ [&](OpenMPLoopInfoStackFrame &frame) {
+ if (!frame.reductionVarToType)
+ frame.reductionVarToType =
+ std::make_unique<llvm::DenseMap<llvm::Value *, llvm::Type *>>();
+ reductionVarToType = frame.reductionVarToType.get();
+ return WalkResult::interrupt();
+ });
+ return reductionVarToType;
+}
+
+/// Scan reduction requires a shared buffer to be allocated to perform the
+/// reduction. The allocation needs to be done outside the parallel region in
+/// which the scan operation is used.
+static llvm::OpenMPIRBuilder::InsertPointTy
+findParallelAllocaIP(llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+ // If there is an alloca insertion point on the stack belonging to a frame
+ // that encloses a parallel op, use it.
+ llvm::OpenMPIRBuilder::InsertPointTy allocaInsertPoint;
+ WalkResult walkResult = moduleTranslation.stackWalk<OpenMPAllocStackFrame>(
+ [&](OpenMPAllocStackFrame &frame) {
+ if (frame.containsParallelOp) {
+ allocaInsertPoint = frame.allocInsertPoint;
+ return WalkResult::interrupt();
+ }
+ return WalkResult::skip();
+ });
+ if (walkResult.wasInterrupted())
+ return allocaInsertPoint;
+ // Otherwise, insert into the entry block of the surrounding function.
+ // If the current IRBuilder InsertPoint is the function's entry, it cannot
+ // also be used for alloca insertion which would result in insertion order
+ // confusion. Create a new BasicBlock for the Builder and use the entry block
+ // for the allocs.
+ // TODO: Create a dedicated alloca BasicBlock at function creation such that
+ // we do not need to move the current InsertPoint here.
+ if (builder.GetInsertBlock() ==
+ &builder.GetInsertBlock()->getParent()->getEntryBlock()) {
+ assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end() &&
+ "Assuming end of basic block");
+ llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(
+ builder.getContext(), "entry", builder.GetInsertBlock()->getParent(),
+ builder.GetInsertBlock()->getNextNode());
+ builder.CreateBr(entryBB);
+ builder.SetInsertPoint(entryBB);
+ }
+
+ llvm::BasicBlock &funcEntryBlock =
+ builder.GetInsertBlock()->getParent()->getEntryBlock();
+ return llvm::OpenMPIRBuilder::InsertPointTy(
+ &funcEntryBlock, funcEntryBlock.getFirstInsertionPt());
+}
+
/// Converts the given region that appears within an OpenMP dialect operation to
/// LLVM IR, creating a branch from the `sourceBlock` to the entry block of the
/// region, and a branch from any block with an successor-less OpenMP terminator
@@ -1414,7 +1532,8 @@ initReductionVars(OP op, ArrayRef<BlockArgument> reductionArgs,
SmallVectorImpl<llvm::Value *> &privateReductionVariables,
DenseMap<Value, llvm::Value *> &reductionVariableMap,
llvm::ArrayRef<bool> isByRef,
- SmallVectorImpl<DeferredStore> &deferredStores) {
+ SmallVectorImpl<DeferredStore> &deferredStores,
+ bool isInScanRegion = false) {
if (op.getNumReductionVars() == 0)
return success();
@@ -1451,11 +1570,17 @@ initReductionVars(OP op, ArrayRef<BlockArgument> reductionArgs,
for (auto [data, addr] : deferredStores)
builder.CreateStore(data, addr);
+ llvm::DenseMap<llvm::Value *, llvm::Type *> *reductionVarToType =
+ findReductionVarTypes(moduleTranslation);
// Before the loop, store the initial values of reductions into reduction
// variables. Although this could be done after allocas, we don't want to mess
// up with the alloca insertion point.
for (unsigned i = 0; i < op.getNumReductionVars(); ++i) {
SmallVector<llvm::Value *, 1> phis;
+ llvm::Type *reductionType =
+ moduleTranslation.convertType(reductionDecls[i].getType());
+ if (isInScanRegion && reductionVarToType != nullptr)
+ (*reductionVarToType)[privateReductionVariables[i]] = reductionType;
// map block argument to initializer region
mapInitializationArgs(op, moduleTranslation, builder, reductionDecls,
@@ -4406,11 +4531,15 @@ convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder,
return failure();
assert(afterAllocas.get()->getSinglePredecessor());
+ bool isInScanRegion =
+ wsloopOp.getReductionMod() && (wsloopOp.getReductionMod().value() ==
+ mlir::omp::ReductionModifier::inscan);
if (failed(initReductionVars(wsloopOp, reductionArgs, builder,
moduleTranslation,
afterAllocas.get()->getSinglePredecessor(),
reductionDecls, privateReductionVariables,
- reductionVariableMap, isByRef, deferredStores)))
+ reductionVariableMap, isByRef, deferredStores,
+ isInScanRegion)))
return failure();
// For `reduction(task, ...)` open a task-reduction scope for the worksharing
@@ -4432,6 +4561,10 @@ convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder,
std::optional<omp::ScheduleModifier> scheduleMod = wsloopOp.getScheduleMod();
bool isSimd = wsloopOp.getScheduleSimd();
bool loopNeedsBarrier = !wsloopOp.getNowait();
+ // TODO: Linear clause support needs to be enabled for scan reduction.
+ if (isInScanRegion)
+ assert(wsloopOp.getLinearVars().empty() &&
+ "Linear clause support is not enabled with scan reduction");
// The only legal way for the direct parent to be omp.distribute is that this
// represents 'distribute parallel do'. Otherwise, this is a regular
@@ -4469,21 +4602,93 @@ convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder,
if (failed(handleError(regionBlock, opInst)))
return failure();
+ // Generates the loop body for a worksharing loop, including linear-variable
+ // handling and the call into the OpenMPIRBuilder's worksharing-loop helper.
+ // For scan reductions this lambda is invoked twice: once for the input loop
+ // and once for the scan loop.
+ const auto &&wsloopCodeGen = [&](llvm::CanonicalLoopInfo *loopInfo,
+ bool noLoopMode,
+ bool inputScanLoop) -> LogicalResult {
+ // Emit Initialization and Update IR for linear variables
+ if (!wsloopOp.getLinearVars().empty()) {
+ linearClauseProcessor.initLinearVar(builder, moduleTranslation,
+ loopInfo->getPreheader());
+ llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
+ moduleTranslation.getOpenMPBuilder()->createBarrier(
+ builder.saveIP(), llvm::omp::OMPD_barrier);
+ if (failed(handleError(afterBarrierIP, *loopOp)))
+ return failure();
+ builder.restoreIP(*afterBarrierIP);
+ linearClauseProcessor.updateLinearVar(builder, loopInfo->getBody(),
+ loopInfo->getIndVar());
+ linearClauseProcessor.splitLinearFiniBB(builder, loopInfo->getExit());
+ }
+
+ builder.SetInsertPoint(*regionBlock, (*regionBlock)->begin());
+
+ for (size_t index = 0; index < wsloopOp.getLinearVars().size(); index++)
+ linearClauseProcessor.rewriteInPlace(builder, loopInfo->getBody(),
+ loopInfo->getLatch(), index);
+
+ llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
+ ompBuilder->applyWorkshareLoop(
+ ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
+ convertToScheduleKind(schedule), chunk, isSimd,
+ scheduleMod == omp::ScheduleModifier::monotonic,
+ scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
+ workshareLoopType, noLoopMode, hasDistSchedule, distScheduleChunk);
+
+ if (failed(handleError(wsloopIP, opInst)))
+ return failure();
+
+ // Emit finalization for linear vars.
+ if (!wsloopOp.getLinearVars().empty()) {
+ llvm::OpenMPIRBuilder::InsertPointTy oldIP = builder.saveIP();
+ assert(loopInfo->getLastIter() &&
+ "`lastiter` in CanonicalLoopInfo is nullptr");
+ llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
+ linearClauseProcessor.finalizeLinearVar(builder, moduleTranslation,
+ loopInfo->getLastIter());
+ if (failed(handleError(afterBarrierIP, *loopOp)))
+ return failure();
+
+ builder.restoreIP(oldIP);
+ }
+
+ // For scan reductions, the cancellation finalization callback is popped
+ // only after the scan (second) loop has been generated.
+ if (!inputScanLoop || !isInScanRegion)
+ popCancelFinalizationCB(cancelTerminators, *ompBuilder, wsloopIP.get());
+
+ return success();
+ };
+
llvm::CanonicalLoopInfo *loopInfo = findCurrentLoopInfo(moduleTranslation);
- // Emit Initialization and Update IR for linear variables
- if (!wsloopOp.getLinearVars().empty()) {
- linearClauseProcessor.initLinearVar(builder, moduleTranslation,
- loopInfo->getPreheader());
- llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
- moduleTranslation.getOpenMPBuilder()->createBarrier(
- builder.saveIP(), llvm::omp::OMPD_barrier);
- if (failed(handleError(afterBarrierIP, *loopOp)))
+ if (isInScanRegion) {
+ // Emit the scan reduction combiner between the input loop and the scan
+ // loop, operating on the per-iteration partial values stored in the shared
+ // buffer.
+ auto inputLoopFinishIp = loopInfo->getAfterIP();
+ builder.restoreIP(inputLoopFinishIp);
+ SmallVector<OwningReductionGen> owningReductionGens;
+ SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
+ SmallVector<llvm::OpenMPIRBuilder::ReductionInfo, 2> reductionInfos;
+ SmallVector<OwningDataPtrPtrReductionGen> owningReductionGenRefDataPtrGens;
+ collectReductionInfo(wsloopOp, builder, moduleTranslation, reductionDecls,
+ owningReductionGens, owningAtomicReductionGens,
+ owningReductionGenRefDataPtrGens,
+ privateReductionVariables, reductionInfos, isByRef);
+ llvm::BasicBlock *cont = splitBB(builder, false, "omp.scan.loop.cont");
+ llvm::ScanInfo *scanInfo = findScanInfo(moduleTranslation);
+ llvm::OpenMPIRBuilder::InsertPointOrErrorTy redIP =
+ ompBuilder->emitScanReduction(builder.saveIP(), reductionInfos,
+ scanInfo);
+ if (failed(handleError(redIP, opInst)))
return failure();
- builder.restoreIP(*afterBarrierIP);
- linearClauseProcessor.updateLinearVar(builder, loopInfo->getBody(),
- loopInfo->getIndVar());
- linearClauseProcessor.splitLinearFiniBB(builder, loopInfo->getExit());
+
+ builder.restoreIP(*redIP);
+ builder.CreateBr(cont);
}
builder.SetInsertPoint(*regionBlock, (*regionBlock)->begin());
@@ -4502,50 +4707,41 @@ convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder,
noLoopMode = true;
}
- for (size_t index = 0; index < wsloopOp.getLinearVars().size(); index++)
- linearClauseProcessor.rewriteInPlace(builder, loopInfo->getBody(),
- loopInfo->getLatch(), index);
-
- llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
- ompBuilder->applyWorkshareLoop(
- ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
- convertToScheduleKind(schedule), chunk, isSimd,
- scheduleMod == omp::ScheduleModifier::monotonic,
- scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
- workshareLoopType, noLoopMode, hasDistSchedule, distScheduleChunk);
-
- if (failed(handleError(wsloopIP, opInst)))
+ // For scan loops, the input loop does not pop the cancellation finalization
+ // callback; that happens after the scan loop is generated below.
+ bool inputScanLoop = isInScanRegion;
+ if (failed(wsloopCodeGen(loopInfo, noLoopMode, inputScanLoop)))
return failure();
+ inputScanLoop = false;
- // Emit finalization and in-place rewrites for linear vars.
- if (!wsloopOp.getLinearVars().empty()) {
- llvm::OpenMPIRBuilder::InsertPointTy oldIP = builder.saveIP();
- assert(loopInfo->getLastIter() &&
- "`lastiter` in CanonicalLoopInfo is nullptr");
- llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
- linearClauseProcessor.finalizeLinearVar(builder, moduleTranslation,
- loopInfo->getLastIter());
- if (failed(handleError(afterBarrierIP, *loopOp)))
+ if (isInScanRegion) {
+ llvm::CanonicalLoopInfo *scanLoopInfo =
+ findCurrentScanLoopInfo(moduleTranslation);
+ if (failed(wsloopCodeGen(scanLoopInfo, noLoopMode, inputScanLoop)))
+ return failure();
+ SmallVector<Region *> reductionRegions;
+ llvm::transform(reductionDecls, std::back_inserter(reductionRegions),
+ [](omp::DeclareReductionOp reductionDecl) {
+ return &reductionDecl.getCleanupRegion();
+ });
+ if (failed(inlineOmpRegionCleanup(
+ reductionRegions, privateReductionVariables, moduleTranslation,
+ builder, "omp.reduction.cleanup")))
return failure();
+ } else {
+ // Close the task-reduction scope before the worksharing reduction combine.
+ if (isTaskReductionMod)
+ emitTaskReductionModifierFini(/*isWorksharing=*/true, builder,
+ moduleTranslation);
- builder.restoreIP(oldIP);
+ // Process the reductions if required.
+ if (failed(createReductionsAndCleanup(
+ wsloopOp, builder, moduleTranslation, allocaIP, reductionDecls,
+ privateReductionVariables, isByRef, wsloopOp.getNowait(),
+ /*isTeamsReduction=*/false)))
+ return failure();
}
- // Set the correct branch target for task cancellation
- popCancelFinalizationCB(cancelTerminators, *ompBuilder, wsloopIP.get());
-
- // Close the task-reduction scope before the worksharing reduction combine.
- if (isTaskReductionMod)
- emitTaskReductionModifierFini(/*isWorksharing=*/true, builder,
- moduleTranslation);
-
- // Process the reductions if required.
- if (failed(createReductionsAndCleanup(
- wsloopOp, builder, moduleTranslation, allocaIP, reductionDecls,
- privateReductionVariables, isByRef, wsloopOp.getNowait(),
- /*isTeamsReduction=*/false)))
- return failure();
-
return cleanupPrivateVars(wsloopOp, builder, moduleTranslation,
wsloopOp.getLoc(), privateVarsInfo);
}
@@ -4579,6 +4775,20 @@ convertOmpParallel(omp::ParallelOp opInst, llvm::IRBuilderBase &builder,
opInst.getReductionMod() == omp::ReductionModifier::task &&
opInst.getNumReductionVars() > 0;
+ // Mark the enclosing alloca stack frame as containing a parallel op. Scan
+ // reductions use the alloca insertion point of the function enclosing the
+ // parallel region to allocate their shared temporary buffer.
+ bool foundParallelOp = false;
+ moduleTranslation.stackWalk<OpenMPAllocStackFrame>(
+ [&](OpenMPAllocStackFrame &frame) {
+ if (foundParallelOp) {
+ frame.containsParallelOp = true;
+ return WalkResult::interrupt();
+ }
+ foundParallelOp = true;
+ return WalkResult::skip();
+ });
+
auto bodyGenCB =
[&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) -> llvm::Error {
@@ -4972,6 +5182,99 @@ convertOmpSimd(Operation &opInst, llvm::IRBuilderBase &builder,
privateVarsInfo);
}
+static LogicalResult
+convertOmpScan(Operation &opInst, llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+ if (failed(checkImplementationStatus(opInst)))
+ return failure();
+ auto scanOp = cast<omp::ScanOp>(opInst);
+ bool isInclusive = scanOp.hasInclusiveVars();
+ SmallVector<llvm::Value *> llvmScanVars;
+ SmallVector<llvm::Type *> llvmScanVarsType;
+ mlir::OperandRange mlirScanVars = scanOp.getInclusiveVars();
+ if (!isInclusive)
+ mlirScanVars = scanOp.getExclusiveVars();
+
+ llvm::DenseMap<llvm::Value *, llvm::Type *> *reductionVarToType =
+ findReductionVarTypes(moduleTranslation);
+ for (auto val : mlirScanVars) {
+ llvm::Value *llvmVal = moduleTranslation.lookupValue(val);
+ llvmScanVars.push_back(llvmVal);
+ llvmScanVarsType.push_back((*reductionVarToType)[llvmVal]);
+ }
+ llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
+ findParallelAllocaIP(builder, moduleTranslation);
+ llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
+ llvm::ScanInfo *scanInfo = findScanInfo(moduleTranslation);
+ llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
+ moduleTranslation.getOpenMPBuilder()->createScan(
+ ompLoc, allocaIP, llvmScanVars, llvmScanVarsType, isInclusive,
+ scanInfo);
+ if (failed(handleError(afterIP, opInst)))
+ return failure();
+ builder.restoreIP(*afterIP);
+ return success();
+}
+
+/// Re-initialize the scan reduction variables to their identity at the start of
+/// each input-loop iteration of a scan reduction. This is required because the
+/// OpenMPIRBuilder stores the per-iteration reduction value into the scan
+/// buffer (`buffer[i] = red`) and `emitScanReduction` then computes the prefix
+/// sum across the buffer. Without resetting `red` to the reduction identity
+/// each iteration, the buffer would hold a running sum and the prefix sum would
+/// be computed twice. This reset only applies to the input loop; in the scan
+/// loop the reduction variable is loaded back from the buffer.
+static LogicalResult
+initScanReductionVars(omp::LoopNestOp loopOp, llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+ auto wsloopOp = loopOp->getParentOfType<omp::WsloopOp>();
+ if (!wsloopOp || !wsloopOp.getReductionMod() ||
+ wsloopOp.getReductionMod().value() != omp::ReductionModifier::inscan)
+ return success();
+
+ // Only reset in the input loop; in the scan loop the reduction variable holds
+ // the value loaded from the buffer and must not be overwritten.
+ llvm::ScanInfo *scanInfo = findScanInfo(moduleTranslation);
+ if (!scanInfo || !scanInfo->OMPFirstScanLoop)
+ return success();
+
+ unsigned numReductions = wsloopOp.getNumReductionVars();
+ if (numReductions == 0)
+ return success();
+
+ SmallVector<omp::DeclareReductionOp> reductionDecls;
+ collectReductionDecls(wsloopOp, reductionDecls);
+ ArrayRef<bool> isByRef = getIsByRef(wsloopOp.getReductionByref());
+ MutableArrayRef<BlockArgument> reductionArgs =
+ cast<omp::BlockArgOpenMPOpInterface>(wsloopOp.getOperation())
+ .getReductionBlockArgs();
+
+ DenseMap<Value, llvm::Value *> reductionVariableMap;
+ for (unsigned i = 0; i < numReductions; ++i)
+ reductionVariableMap.try_emplace(
+ wsloopOp.getReductionVars()[i],
+ moduleTranslation.lookupValue(reductionArgs[i]));
+
+ for (unsigned i = 0; i < numReductions; ++i) {
+ // Scan reductions only support by-value (scalar) reductions.
+ if (isByRef[i])
+ continue;
+ SmallVector<llvm::Value *, 1> phis;
+ mapInitializationArgs(wsloopOp, moduleTranslation, builder, reductionDecls,
+ reductionVariableMap, i);
+ if (failed(inlineConvertOmpRegions(
+ reductionDecls[i].getInitializerRegion(),
+ "omp.scan.reduction.init", builder, moduleTranslation, &phis)))
+ return failure();
+ assert(phis.size() == 1 &&
+ "expected one value to be yielded from the reduction init region");
+ setInsertPointForPossiblyEmptyBlock(builder);
+ builder.CreateStore(phis[0],
+ moduleTranslation.lookupValue(reductionArgs[i]));
+ }
+ return success();
+}
+
/// Converts an OpenMP loop nest into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpLoopNest(Operation &opInst, llvm::IRBuilderBase &builder,
@@ -5004,6 +5307,10 @@ convertOmpLoopNest(Operation &opInst, llvm::IRBuilderBase &builder,
// Convert the body of the loop.
builder.restoreIP(ip);
+ // For scan reductions, reset the reduction variables to their identity at
+ // the start of each input-loop iteration, before the input phase runs.
+ if (failed(initScanReductionVars(loopOp, builder, moduleTranslation)))
+ return llvm::make_error<PreviouslyReportedError>();
llvm::Expected<llvm::BasicBlock *> regionBlock = convertOmpOpRegions(
loopOp.getRegion(), "omp.loop_nest.region", builder, moduleTranslation);
if (!regionBlock)
@@ -5036,6 +5343,46 @@ convertOmpLoopNest(Operation &opInst, llvm::IRBuilderBase &builder,
computeIP = loopInfos.front()->getPreheaderIP();
}
+ // If this loop is the worksharing loop of a scan reduction, generate a
+ // pair of canonical loops (an input loop and a scan loop) instead of a
+ // single loop. The `scan` directive in the body is translated against the
+ // `ScanInfo` recorded here.
+ bool isInScanRegion = false;
+ if (auto wsloopOp = loopOp->getParentOfType<omp::WsloopOp>())
+ isInScanRegion =
+ wsloopOp.getReductionMod() && (wsloopOp.getReductionMod().value() ==
+ mlir::omp::ReductionModifier::inscan);
+ if (isInScanRegion) {
+ llvm::Expected<llvm::ScanInfo *> res = ompBuilder->scanInfoInitialize();
+ if (failed(handleError(res, *loopOp)))
+ return failure();
+ llvm::ScanInfo *scanInfo = res.get();
+ moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
+ [&](OpenMPLoopInfoStackFrame &frame) {
+ frame.scanInfo = scanInfo;
+ return WalkResult::interrupt();
+ });
+ llvm::Expected<llvm::SmallVector<llvm::CanonicalLoopInfo *>> loopResults =
+ ompBuilder->createCanonicalScanLoops(
+ loc, bodyGen, lowerBound, upperBound, step,
+ /*IsSigned=*/true, loopOp.getLoopInclusive(), computeIP, "loop",
+ scanInfo);
+
+ if (failed(handleError(loopResults, *loopOp)))
+ return failure();
+ llvm::CanonicalLoopInfo *inputLoop = loopResults.get().front();
+ llvm::CanonicalLoopInfo *scanLoop = loopResults.get().back();
+ moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
+ [&](OpenMPLoopInfoStackFrame &frame) {
+ frame.loopInfo = inputLoop;
+ frame.scanloopInfo = scanLoop;
+ return WalkResult::interrupt();
+ });
+ builder.restoreIP(scanLoop->getAfterIP());
+ // TODO: tiling and collapse are not yet implemented for scan reduction.
+ return success();
+ }
+
llvm::Expected<llvm::CanonicalLoopInfo *> loopResult =
ompBuilder->createCanonicalLoop(
loc, bodyGen, lowerBound, upperBound, step,
@@ -9454,6 +9801,9 @@ LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation(
.Case([&](omp::WsloopOp) {
return convertOmpWsloop(*op, builder, moduleTranslation);
})
+ .Case([&](omp::ScanOp) {
+ return convertOmpScan(*op, builder, moduleTranslation);
+ })
.Case([&](omp::SimdOp) {
return convertOmpSimd(*op, builder, moduleTranslation);
})
diff --git a/mlir/test/Target/LLVMIR/openmp-reduction-scan.mlir b/mlir/test/Target/LLVMIR/openmp-reduction-scan.mlir
new file mode 100644
index 0000000000000..c6b8daccad313
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/openmp-reduction-scan.mlir
@@ -0,0 +1,123 @@
+// RUN: mlir-translate -mlir-to-llvmir %s | FileCheck %s
+omp.declare_reduction @add_reduction_i32 : i32 init {
+^bb0(%arg0: i32):
+ %0 = llvm.mlir.constant(0 : i32) : i32
+ omp.yield(%0 : i32)
+} combiner {
+^bb0(%arg0: i32, %arg1: i32):
+ %0 = llvm.add %arg0, %arg1 : i32
+ omp.yield(%0 : i32)
+}
+// CHECK-LABEL: @scan_reduction
+llvm.func @scan_reduction() {
+ %0 = llvm.mlir.constant(1 : i64) : i64
+ %1 = llvm.alloca %0 x i32 {bindc_name = "z"} : (i64) -> !llvm.ptr
+ %3 = llvm.alloca %0 x i32 {bindc_name = "y"} : (i64) -> !llvm.ptr
+ %5 = llvm.alloca %0 x i32 {bindc_name = "x"} : (i64) -> !llvm.ptr
+ %7 = llvm.alloca %0 x i32 {bindc_name = "k"} : (i64) -> !llvm.ptr
+ %10 = llvm.mlir.constant(100 : i32) : i32
+ %11 = llvm.mlir.constant(1 : i32) : i32
+ %12 = llvm.mlir.constant(0 : i32) : i32
+ %13 = llvm.mlir.constant(100 : index) : i64
+ %14 = llvm.mlir.addressof @_QFEa : !llvm.ptr
+ %15 = llvm.mlir.addressof @_QFEb : !llvm.ptr
+ omp.parallel {
+ %37 = llvm.mlir.constant(1 : i64) : i64
+ %38 = llvm.alloca %37 x i32 {bindc_name = "k", pinned} : (i64) -> !llvm.ptr
+ %39 = llvm.mlir.constant(1 : i64) : i64
+ omp.wsloop reduction(mod: inscan, @add_reduction_i32 %5 -> %arg0 : !llvm.ptr) {
+ omp.loop_nest (%arg1) : i32 = (%11) to (%10) inclusive step (%11) {
+ llvm.store %arg1, %38 : i32, !llvm.ptr
+ %40 = llvm.load %arg0 : !llvm.ptr -> i32
+ %41 = llvm.load %38 : !llvm.ptr -> i32
+ %42 = llvm.sext %41 : i32 to i64
+ %50 = llvm.getelementptr %14[%42] : (!llvm.ptr, i64) -> !llvm.ptr, i32
+ %51 = llvm.load %50 : !llvm.ptr -> i32
+ %52 = llvm.add %40, %51 : i32
+ llvm.store %52, %arg0 : i32, !llvm.ptr
+ omp.scan inclusive(%arg0 : !llvm.ptr)
+ llvm.store %arg1, %38 : i32, !llvm.ptr
+ %53 = llvm.load %arg0 : !llvm.ptr -> i32
+ %54 = llvm.load %38 : !llvm.ptr -> i32
+ %55 = llvm.sext %54 : i32 to i64
+ %63 = llvm.getelementptr %15[%55] : (!llvm.ptr, i64) -> !llvm.ptr, i32
+ llvm.store %53, %63 : i32, !llvm.ptr
+ omp.yield
+ }
+ }
+ omp.terminator
+ }
+ llvm.return
+}
+llvm.mlir.global internal @_QFEa() {addr_space = 0 : i32} : !llvm.array<100 x i32> {
+ %0 = llvm.mlir.zero : !llvm.array<100 x i32>
+ llvm.return %0 : !llvm.array<100 x i32>
+}
+llvm.mlir.global internal @_QFEb() {addr_space = 0 : i32} : !llvm.array<100 x i32> {
+ %0 = llvm.mlir.zero : !llvm.array<100 x i32>
+ llvm.return %0 : !llvm.array<100 x i32>
+}
+//CHECK: %vla = alloca ptr, align 8
+//CHECK: omp_parallel
+//CHECK: store ptr %vla, ptr %gep_vla, align 8
+//CHECK: @__kmpc_fork_call
+//CHECK: void @scan_reduction..omp_par
+//CHECK: %[[BUFF_PTR:.+]] = load ptr, ptr %gep_vla
+//CHECK: @__kmpc_masked
+//CHECK: @__kmpc_barrier
+//CHECK: @__kmpc_masked
+//CHECK: @__kmpc_barrier
+//CHECK: omp.scan.loop.cont:
+//CHECK: @__kmpc_masked
+//CHECK: @__kmpc_barrier
+//CHECK: %[[FREE_VAR:.+]] = load ptr, ptr %[[BUFF_PTR]], align 8
+//CHECK: %[[ARRLAST:.+]] = getelementptr inbounds i32, ptr %[[FREE_VAR]], i32 100
+//CHECK: %[[RES:.+]] = load i32, ptr %[[ARRLAST]], align 4
+//CHECK: store i32 %[[RES]], ptr %loadgep{{.*}}, align 4
+//CHECK: tail call void @free(ptr %[[FREE_VAR]])
+//CHECK: @__kmpc_end_masked
+//CHECK: omp.inscan.dispatch{{.*}}: ; preds = %omp_loop.body{{.*}}
+//CHECK: %[[BUFFVAR:.+]] = load ptr, ptr %[[BUFF_PTR]], align 8
+//CHECK: %[[arrayOffset1:.+]] = getelementptr inbounds i32, ptr %[[BUFFVAR]], i32 %{{.*}}
+//CHECK: %[[BUFFVAL1:.+]] = load i32, ptr %[[arrayOffset1]], align 4
+//CHECK: store i32 %[[BUFFVAL1]], ptr %{{.*}}, align 4
+//CHECK: %[[LOG:.+]] = call double @llvm.log2.f64(double 1.000000e+02) #0
+//CHECK: %[[CEIL:.+]] = call double @llvm.ceil.f64(double %[[LOG]]) #0
+//CHECK: %[[UB:.+]] = fptoui double %[[CEIL]] to i32
+//CHECK: br label %omp.outer.log.scan.body
+//CHECK: omp.outer.log.scan.body:
+//CHECK: %[[K:.+]] = phi i32 [ 0, %{{.*}} ], [ %[[NEXTK:.+]], %omp.inner.log.scan.exit ]
+//CHECK: %[[I:.+]] = phi i32 [ 1, %{{.*}} ], [ %[[NEXTI:.+]], %omp.inner.log.scan.exit ]
+//CHECK: %[[CMP1:.+]] = icmp uge i32 99, %[[I]]
+//CHECK: br i1 %[[CMP1]], label %omp.inner.log.scan.body, label %omp.inner.log.scan.exit
+//CHECK: omp.inner.log.scan.exit: ; preds = %omp.inner.log.scan.body, %omp.outer.log.scan.body
+//CHECK: %[[NEXTK]] = add nuw i32 %[[K]], 1
+//CHECK: %[[NEXTI]] = shl nuw i32 %[[I]], 1
+//CHECK: %[[CMP2:.+]] = icmp ne i32 %[[NEXTK]], %[[UB]]
+//CHECK: br i1 %[[CMP2]], label %omp.outer.log.scan.body, label %omp.outer.log.scan.exit
+//CHECK: omp.outer.log.scan.exit: ; preds = %omp.inner.log.scan.exit
+//CHECK: @__kmpc_end_masked
+//CHECK: omp.inner.log.scan.body: ; preds = %omp.inner.log.scan.body, %omp.outer.log.scan.body
+//CHECK: %[[CNT:.+]] = phi i32 [ 99, %omp.outer.log.scan.body ], [ %[[CNTNXT:.+]], %omp.inner.log.scan.body ]
+//CHECK: %[[BUFF:.+]] = load ptr, ptr %[[BUFF_PTR]]
+//CHECK: %[[IND1:.+]] = add i32 %[[CNT]], 1
+//CHECK: %[[IND1PTR:.+]] = getelementptr inbounds i32, ptr %[[BUFF]], i32 %[[IND1]]
+//CHECK: %[[IND2:.+]] = sub nuw i32 %[[IND1]], %[[I]]
+//CHECK: %[[IND2PTR:.+]] = getelementptr inbounds i32, ptr %[[BUFF]], i32 %[[IND2]]
+//CHECK: %[[IND1VAL:.+]] = load i32, ptr %[[IND1PTR]], align 4
+//CHECK: %[[IND2VAL:.+]] = load i32, ptr %[[IND2PTR]], align 4
+//CHECK: %[[REDVAL:.+]] = add i32 %[[IND1VAL]], %[[IND2VAL]]
+//CHECK: store i32 %[[REDVAL]], ptr %[[IND1PTR]], align 4
+//CHECK: %[[CNTNXT]] = sub nuw i32 %[[CNT]], 1
+//CHECK: %[[CMP3:.+]] = icmp uge i32 %[[CNTNXT]], %[[I]]
+//CHECK: br i1 %[[CMP3]], label %omp.inner.log.scan.body, label %omp.inner.log.scan.exit
+//CHECK: omp.inscan.dispatch: ; preds = %omp_loop.body
+//CHECK: br i1 true, label %omp.before.scan.bb, label %omp.after.scan.bb
+//CHECK: omp.before.scan.bb:
+//CHECK: store i32 0, ptr %[[REDPRIV:.+]], align 4
+//CHECK: omp.loop_nest.region: ; preds = %omp.before.scan.bb
+//CHECK: %[[BUFFER:.+]] = load ptr, ptr %loadgep_vla, align 8
+//CHECK: %[[ARRAYOFFSET2:.+]] = getelementptr inbounds i32, ptr %[[BUFFER]], i32 %{{.*}}
+//CHECK-NEXT: %[[REDPRIVVAL:.+]] = load i32, ptr %{{.*}}, align 4
+//CHECK: store i32 %[[REDPRIVVAL]], ptr %[[ARRAYOFFSET2]], align 4
+//CHECK: br label %omp.scan.loop.exit
diff --git a/mlir/test/Target/LLVMIR/openmp-todo.mlir b/mlir/test/Target/LLVMIR/openmp-todo.mlir
index 71e8628595aab..7edf88b5ea559 100644
--- a/mlir/test/Target/LLVMIR/openmp-todo.mlir
+++ b/mlir/test/Target/LLVMIR/openmp-todo.mlir
@@ -120,10 +120,10 @@ atomic {
llvm.atomicrmw fadd %arg2, %2 monotonic : !llvm.ptr, f32
omp.yield
}
-llvm.func @scan_reduction(%lb : i32, %ub : i32, %step : i32, %x : !llvm.ptr) {
- // expected-error at below {{not yet implemented: Unhandled clause reduction with modifier in omp.wsloop operation}}
- // expected-error at below {{LLVM Translation failed for operation: omp.wsloop}}
- omp.wsloop reduction(mod:inscan, @add_f32 %x -> %prv : !llvm.ptr) {
+llvm.func @simd_reduction(%lb : i32, %ub : i32, %step : i32, %x : !llvm.ptr) {
+ // expected-error at below {{not yet implemented: Unhandled clause reduction with modifier in omp.simd operation}}
+ // expected-error at below {{LLVM Translation failed for operation: omp.simd}}
+ omp.simd reduction(mod:inscan, @add_f32 %x -> %prv : !llvm.ptr) {
omp.loop_nest (%iv) : i32 = (%lb) to (%ub) step (%step) {
omp.scan inclusive(%prv : !llvm.ptr)
omp.yield
@@ -162,6 +162,39 @@ llvm.func @parallel_task_reduction_modifier_byref(%x : !llvm.ptr) {
// -----
+omp.declare_reduction @add_f32 : f32
+init {
+^bb0(%arg: f32):
+ %0 = llvm.mlir.constant(0.0 : f32) : f32
+ omp.yield (%0 : f32)
+}
+combiner {
+^bb1(%arg0: f32, %arg1: f32):
+ %1 = llvm.fadd %arg0, %arg1 : f32
+ omp.yield (%1 : f32)
+}
+atomic {
+^bb2(%arg2: !llvm.ptr, %arg3: !llvm.ptr):
+ %2 = llvm.load %arg3 : !llvm.ptr -> f32
+ llvm.atomicrmw fadd %arg2, %2 monotonic : !llvm.ptr, f32
+ omp.yield
+}
+llvm.func @scan_reduction(%lb : i32, %ub : i32, %step : i32, %x : !llvm.ptr) {
+ // expected-error at below {{LLVM Translation failed for operation: omp.wsloop}}
+ omp.wsloop reduction(mod:inscan, @add_f32 %x -> %prv : !llvm.ptr) {
+ // expected-error at below {{LLVM Translation failed for operation: omp.loop_nest}}
+ omp.loop_nest (%iv) : i32 = (%lb) to (%ub) step (%step) {
+ // expected-error at below {{not yet implemented: Unhandled clause exclusive in omp.scan operation}}
+ // expected-error at below {{LLVM Translation failed for operation: omp.scan}}
+ omp.scan exclusive(%prv : !llvm.ptr)
+ omp.yield
+ }
+ }
+ llvm.return
+}
+
+// -----
+
llvm.func @single_allocate(%x : !llvm.ptr) {
// expected-error at below {{not yet implemented: Unhandled clause allocate in omp.single operation}}
// expected-error at below {{LLVM Translation failed for operation: omp.single}}
diff --git a/openmp/runtime/test/scan/scan.f90 b/openmp/runtime/test/scan/scan.f90
new file mode 100644
index 0000000000000..76263508105d0
--- /dev/null
+++ b/openmp/runtime/test/scan/scan.f90
@@ -0,0 +1,38 @@
+! RUN: %flang %flags %openmp_flags -fopenmp-version=51 %s -o %t.exe
+! RUN: %t.exe | FileCheck %s --match-full-lines
+program inclusive_scan
+ implicit none
+ integer, parameter :: n = 100
+ integer a(n), b(n)
+ integer x, k, y, z
+
+ ! initialization
+ x = 0
+ do k = 1, n
+ a(k) = k
+ end do
+
+ ! a(k) is included in the computation of producing results in b(k)
+ !$omp parallel do reduction(inscan, +: x)
+ do k = 1, n
+ x = x + a(k)
+ !$omp scan inclusive(x)
+ b(k) = x
+ end do
+
+ print *,'x =', x
+ do k = 1, 10
+ print *, 'b(', k, ') =', b(k)
+ end do
+end program
+!CHECK: x = 5050
+!CHECK: b( 1 ) = 1
+!CHECK: b( 2 ) = 3
+!CHECK: b( 3 ) = 6
+!CHECK: b( 4 ) = 10
+!CHECK: b( 5 ) = 15
+!CHECK: b( 6 ) = 21
+!CHECK: b( 7 ) = 28
+!CHECK: b( 8 ) = 36
+!CHECK: b( 9 ) = 45
+!CHECK: b( 10 ) = 55
>From 4011dd537d9830ee4a0379cba80413d1e4cdf9c3 Mon Sep 17 00:00:00 2001
From: Chandra Ghale <ghale at pe34genoa.hpc.amslabs.hpecorp.net>
Date: Wed, 1 Jul 2026 02:44:02 -0500
Subject: [PATCH 2/2] formatting correction
---
.../OpenMP/OpenMPToLLVMIRTranslation.cpp | 17 ++++++++---------
1 file changed, 8 insertions(+), 9 deletions(-)
diff --git a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 297ebac51de88..e18cc0df79860 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -4534,12 +4534,11 @@ convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder,
bool isInScanRegion =
wsloopOp.getReductionMod() && (wsloopOp.getReductionMod().value() ==
mlir::omp::ReductionModifier::inscan);
- if (failed(initReductionVars(wsloopOp, reductionArgs, builder,
- moduleTranslation,
- afterAllocas.get()->getSinglePredecessor(),
- reductionDecls, privateReductionVariables,
- reductionVariableMap, isByRef, deferredStores,
- isInScanRegion)))
+ if (failed(initReductionVars(
+ wsloopOp, reductionArgs, builder, moduleTranslation,
+ afterAllocas.get()->getSinglePredecessor(), reductionDecls,
+ privateReductionVariables, reductionVariableMap, isByRef,
+ deferredStores, isInScanRegion)))
return failure();
// For `reduction(task, ...)` open a task-reduction scope for the worksharing
@@ -5262,9 +5261,9 @@ initScanReductionVars(omp::LoopNestOp loopOp, llvm::IRBuilderBase &builder,
SmallVector<llvm::Value *, 1> phis;
mapInitializationArgs(wsloopOp, moduleTranslation, builder, reductionDecls,
reductionVariableMap, i);
- if (failed(inlineConvertOmpRegions(
- reductionDecls[i].getInitializerRegion(),
- "omp.scan.reduction.init", builder, moduleTranslation, &phis)))
+ if (failed(inlineConvertOmpRegions(reductionDecls[i].getInitializerRegion(),
+ "omp.scan.reduction.init", builder,
+ moduleTranslation, &phis)))
return failure();
assert(phis.size() == 1 &&
"expected one value to be yielded from the reduction init region");
More information about the Openmp-commits
mailing list