https://github.com/jsjodin updated https://github.com/llvm/llvm-project/pull/229259
>From 0359ca0f9ebdce4f30bd979ea69f23d0a7e7422e Mon Sep 17 00:00:00 2001 From: Jan Leyonberg <[email protected]> Date: Wed, 7 Oct 2026 13:13:03 -0400 Subject: [PATCH] [CIR][OpenMP] Add support for host_eval so that SPMD kernels can be used This patch adds support for host_eval so that SPMD kernels and in the future num_threads and other clauses can be implemented correctly. Assisted-by: Cursor / Claude Sonnet 5 High --- clang/lib/CIR/CodeGen/CIRGenFunction.h | 26 ++ clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp | 255 +++++++++++++++--- .../CIR/CodeGenOpenMP/not-yet-implemented.c | 9 + .../test/CIR/CodeGenOpenMP/target-host-eval.c | 96 +++++++ .../CIR/CodeGenOpenMP/target-parallel-for.c | 86 +++--- 5 files changed, 409 insertions(+), 63 deletions(-) create mode 100644 clang/test/CIR/CodeGenOpenMP/target-host-eval.c diff --git a/clang/lib/CIR/CodeGen/CIRGenFunction.h b/clang/lib/CIR/CodeGen/CIRGenFunction.h index c51aae7b2a35ca..ea8aaa23b71456 100644 --- a/clang/lib/CIR/CodeGen/CIRGenFunction.h +++ b/clang/lib/CIR/CodeGen/CIRGenFunction.h @@ -2912,6 +2912,32 @@ class CIRGenFunction : public CIRGenTypeCache { // OpenMP Emission //===--------------------------------------------------------------------===// public: + /// The enclosing omp.target's host-evaluated loop bounds -- a normalized + /// [0, tripCount) range matching emitOMPLoopNest's convention -- forwarded + /// as host_eval block arguments and consumed once by the nested + /// omp.wsloop. + struct OMPHostEvalBounds { + mlir::Value zero; + mlir::Value tripCount; + mlir::Value one; + bool applied = false; + }; + std::optional<OMPHostEvalBounds> ompHostEvalBounds; + + /// An RAII object to set (and then restore) ompHostEvalBounds for the + /// extent of a nested loop directive's emission. + struct OMPHostEvalBoundsRAII { + CIRGenFunction &cgf; + std::optional<OMPHostEvalBounds> oldBounds; + + OMPHostEvalBoundsRAII(CIRGenFunction &cgf, + std::optional<OMPHostEvalBounds> newBounds) + : cgf(cgf), oldBounds(std::move(cgf.ompHostEvalBounds)) { + cgf.ompHostEvalBounds = std::move(newBounds); + } + ~OMPHostEvalBoundsRAII() { cgf.ompHostEvalBounds = std::move(oldBounds); } + }; + /// Emits a Sema-synthesized OpenMP helper variable (loop counter, iteration /// variable or pre-init capture) without lifetime markers. These variables /// are emitted between nested combined/composite OpenMP ops, which must be diff --git a/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp b/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp index eb5f3a430b290c..33bdcb659b01fc 100644 --- a/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp @@ -52,6 +52,76 @@ checkSynthesizedClauses(CIRGenFunction &cgf, const OMPExecutableDirective &s, return res; } +/// Returns \p s's nested OpenMP directive -- its body after unwrapping any +/// single-statement compounds -- or null if the body isn't itself a single +/// OpenMP directive. +static const OMPExecutableDirective * +getSingleNestedOMPDirective(const OMPExecutableDirective &s) { + const Stmt *body = + s.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers( + /*IgnoreCaptured=*/true); + return dyn_cast<OMPExecutableDirective>(body); +} + +/// Returns true if \p dir is a leaf construct kind that participates in +/// CIR's "combined" op marking (see hasCombinableNestedLeaf). +static bool isCombinableLeaf(llvm::omp::Directive dir) { + switch (dir) { + case llvm::omp::OMPD_target: + case llvm::omp::OMPD_parallel: + case llvm::omp::OMPD_for: + return true; + default: + return false; + } +} + +/// Returns true if \p s's body is itself an OpenMP directive that combines +/// with \p s for codegen purposes, e.g. explicitly-nested `target` + +/// `parallel` written as separate pragmas rather than `target parallel`. +static bool hasCombinableNestedLeaf(const OMPExecutableDirective &s) { + const OMPExecutableDirective *nested = getSingleNestedOMPDirective(s); + if (!nested) + return false; + return isCombinableLeaf( + llvm::omp::getLeafConstructsOrSelf(nested->getDirectiveKind()).front()); +} + +/// Finds the loop directive nested (possibly transitively) inside \p s. +static const OMPLoopDirective * +findNestedOMPLoopDirective(const OMPExecutableDirective &s) { + const OMPExecutableDirective *nested = getSingleNestedOMPDirective(s); + if (!nested) + return nullptr; + if (const auto *loopDir = dyn_cast<OMPLoopDirective>(nested)) + return loopDir; + return findNestedOMPLoopDirective(*nested); +} + +/// Returns true if \p s is a target SPMD construct: a combined +/// `target parallel for`, or the same construct written with explicitly +/// nested directives, e.g. a `target` whose body is a `parallel` whose body +/// is a `for`. +static bool isTargetSPMD(const OMPExecutableDirective &s) { + switch (s.getDirectiveKind()) { + case llvm::omp::OMPD_target_parallel_for: + return true; + case llvm::omp::OMPD_target: { + const OMPExecutableDirective *parallel = getSingleNestedOMPDirective(s); + if (!parallel) + return false; + if (parallel->getDirectiveKind() == llvm::omp::OMPD_parallel_for) + return true; + if (parallel->getDirectiveKind() != llvm::omp::OMPD_parallel) + return false; + const OMPExecutableDirective *loop = getSingleNestedOMPDirective(*parallel); + return loop && loop->getDirectiveKind() == llvm::omp::OMPD_for; + } + default: + return false; + } +} + static mlir::LogicalResult emitParallelClauses(CIRGenFunction &cgf, CIRGenModule &cgm, CIRGenBuilderTy &builder, mlir::Location loc, @@ -113,7 +183,8 @@ emitParallelOp(CIRGenFunction &cgf, const DirectiveTy &s, "reduction(task: ...) should already be rejected as NYI"); auto parallelOp = mlir::omp::ParallelOp::create(builder, begin, clauseOps); - if (!omp::isLastItemInQueue(item, queue)) + if (!omp::isLastItemInQueue(item, queue) || + hasCombinableNestedLeaf(static_cast<const OMPExecutableDirective &>(s))) parallelOp.setCombined(true); mlir::Block &block = parallelOp.getRegion().emplaceBlock(); @@ -198,6 +269,25 @@ static mlir::LogicalResult emitLoopPreInits(CIRGenFunction &cgf, return emitLoopPreInit(cgf, preInits); } +/// Returns the variables declared by the Sema-generated pre-init statements +/// of an OpenMP loop directive (see emitLoopPreInits). +static llvm::SmallVector<const VarDecl *> +getLoopPreInitVars(const Stmt *preInits) { + llvm::SmallVector<const VarDecl *> vars; + auto addVars = [&](const Stmt *stmt) { + if (const auto *declStmt = dyn_cast<DeclStmt>(stmt)) + for (const Decl *d : declStmt->decls()) + vars.push_back(cast<VarDecl>(d)); + }; + if (!preInits) + return vars; + if (const auto *compound = dyn_cast<CompoundStmt>(preInits)) + llvm::for_each(compound->body(), addVars); + else + addVars(preInits); + return vars; +} + /// Returns the first `continue` in \p s that is not nested in an inner loop, /// i.e. one that targets the loop whose body is \p s. static const ContinueStmt *findLoopBodyContinue(const Stmt *s) { @@ -307,6 +397,34 @@ static Address emitLoopPrivateCounter(CIRGenFunction &cgf, CIRGenModule &cgm, return moldAddr; } +/// Returns the `for` loop associated with \p s, or reports NYI and returns +/// null if the loop can't be emitted yet. Checked before any op is created, +/// so that a failure doesn't leave behind a loop wrapper or SPMD target +/// without its omp.loop_nest. +static const ForStmt *getSupportedLoopForStmt(CIRGenFunction &cgf, + const OMPLoopDirective &s) { + CIRGenModule &cgm = cgf.getCIRGenModule(); + const Stmt *loopStmt = s.getInnermostCapturedStmt()->getCapturedStmt(); + const auto *forStmt = dyn_cast<ForStmt>(loopStmt); + if (!forStmt) { + assert(isa<CXXForRangeStmt>(loopStmt) && + "expected a for or range-based for loop"); + cgm.errorNYI(loopStmt->getSourceRange(), + "range-based for loop in an OpenMP loop directive"); + return nullptr; + } + + // A `continue` lowers to cir.continue, which must be nested in a CIR loop, + // and omp.loop_nest is not one. + if (const ContinueStmt *continueStmt = + findLoopBodyContinue(forStmt->getBody())) { + cgm.errorNYI(continueStmt->getSourceRange(), + "continue in an OpenMP loop body"); + return nullptr; + } + return forStmt; +} + /// Emits the trip count of the loop associated with \p s: Sema's iteration /// count if the loop's precondition holds, and zero otherwise. The iteration /// count is only meaningful when the loop runs at least once; e.g. for @@ -323,6 +441,40 @@ static mlir::Value emitLoopTripCount(CIRGenFunction &cgf, return builder.createSelect(loc, preCond, numIterations, zero); } +/// Computes a target SPMD loop's normalized `[0, tripCount)` bounds at the +/// host insertion point, as builtin-integer values for the enclosing +/// omp.target's host_eval operands. All three are forwarded even though +/// only the trip count is runtime-dependent, since the dialect requires an +/// SPMD loop_nest's bounds to be host-evaluated in full. +/// +/// The pre-init variables emitted here are only visible to the trip count +/// computation. The loop inside the omp.target emits them again, since its +/// isolated region can't use values defined outside of it. +static std::optional<CIRGenFunction::OMPHostEvalBounds> +emitHostEvalLoopBounds(CIRGenFunction &cgf, const OMPLoopDirective &s) { + llvm::SmallVector<const VarDecl *> preInitVars = + getLoopPreInitVars(s.getPreInits()); + llvm::SmallVector<CIRGenFunction::DeclMapRevertingRAII, 4> preInitShadows; + preInitShadows.reserve(preInitVars.size()); + for (const VarDecl *vd : preInitVars) + preInitShadows.emplace_back(cgf, vd); + CIRGenFunction::SymTableScopeTy preInitScope(cgf.symbolTable); + + if (emitLoopPreInits(cgf, s.getPreInits()).failed()) + return std::nullopt; + CIRGenBuilderTy &builder = cgf.getBuilder(); + mlir::Location loc = cgf.getLoc(s.getBeginLoc()); + mlir::Value tripCountCir = emitLoopTripCount(cgf, s); + auto cirIntType = mlir::cast<cir::IntType>(tripCountCir.getType()); + CIRGenFunction::OMPHostEvalBounds hev; + hev.zero = builder.createBuiltinIntCast( + loc, builder.getConstInt(loc, cirIntType, 0)); + hev.tripCount = builder.createBuiltinIntCast(loc, tripCountCir); + hev.one = builder.createBuiltinIntCast( + loc, builder.getConstInt(loc, cirIntType, 1)); + return hev; +} + /// Lowers an OMPLoopDirective's `for` directive to an omp.wsloop + /// omp.loop_nest. static mlir::LogicalResult @@ -340,28 +492,19 @@ emitOMPWorksharingLoop(CIRGenFunction &cgf, const OMPLoopDirective &s, .failed()) return mlir::failure(); - const CapturedStmt *capturedStmt = s.getInnermostCapturedStmt(); - const auto *forStmt = dyn_cast<ForStmt>(capturedStmt->getCapturedStmt()); - if (!forStmt) { - assert(isa<CXXForRangeStmt>(capturedStmt->getCapturedStmt()) && - "expected a for or range-based for loop"); - cgm.errorNYI(capturedStmt->getCapturedStmt()->getSourceRange(), - "range-based for loop in an OpenMP loop directive"); - return mlir::failure(); - } - - // A `continue` lowers to cir.continue, which must be nested in a CIR loop, - // and omp.loop_nest is not one. - if (const ContinueStmt *continueStmt = - findLoopBodyContinue(forStmt->getBody())) { - cgm.errorNYI(continueStmt->getSourceRange(), - "continue in an OpenMP loop body"); + const ForStmt *forStmt = getSupportedLoopForStmt(cgf, s); + if (!forStmt) return mlir::failure(); - } if (emitLoopPreInits(cgf, s.getPreInits()).failed()) return mlir::failure(); + // True when the enclosing omp.target already computed this loop's trip + // count (see emitHostEvalLoopBounds) and forwarded it via + // cgf.ompHostEvalBounds. + bool consumingHostEval = + cgf.ompHostEvalBounds && !cgf.ompHostEvalBounds->applied; + // Allocate storage for Sema's normalized 0-based loop counter. const auto *ivDecl = cast<VarDecl>(cast<DeclRefExpr>(s.getIterationVariable())->getDecl()); @@ -383,13 +526,22 @@ emitOMPWorksharingLoop(CIRGenFunction &cgf, const OMPLoopDirective &s, vd, emitLoopPrivateCounter(cgf, cgm, loc, privateVd, clauseOps)); } - mlir::Value tripCountCir = emitLoopTripCount(cgf, s); - auto cirIntType = mlir::cast<cir::IntType>(tripCountCir.getType()); - mlir::Value zero = builder.createBuiltinIntCast( - loc, builder.getConstInt(loc, cirIntType, 0)); - mlir::Value one = builder.createBuiltinIntCast( - loc, builder.getConstInt(loc, cirIntType, 1)); - mlir::Value tripCount = builder.createBuiltinIntCast(loc, tripCountCir); + mlir::Value zero, tripCount, one; + if (consumingHostEval) { + // Consume the host_eval bounds forwarded by the enclosing omp.target. + cgf.ompHostEvalBounds->applied = true; + zero = cgf.ompHostEvalBounds->zero; + tripCount = cgf.ompHostEvalBounds->tripCount; + one = cgf.ompHostEvalBounds->one; + } else { + mlir::Value tripCountCir = emitLoopTripCount(cgf, s); + auto cirIntType = mlir::cast<cir::IntType>(tripCountCir.getType()); + zero = builder.createBuiltinIntCast( + loc, builder.getConstInt(loc, cirIntType, 0)); + one = builder.createBuiltinIntCast(loc, + builder.getConstInt(loc, cirIntType, 1)); + tripCount = builder.createBuiltinIntCast(loc, tripCountCir); + } auto wsloopOp = mlir::omp::WsloopOp::create(builder, loc, clauseOps); mlir::Block *innerBlock = new mlir::Block(); @@ -651,25 +803,68 @@ emitTargetOp(CIRGenFunction &cgf, const DirectiveTy &s, if (mlir::failed(emitOMPTargetImplicitCaptures(cgf, s, mapSyms))) return mlir::failure(); - // Use generic for now. + const auto &execDir = static_cast<const OMPExecutableDirective &>(s); + bool isSPMD = isTargetSPMD(execDir); + + const OMPLoopDirective *loopDir = nullptr; + if (isSPMD) { + loopDir = dyn_cast<OMPLoopDirective>(&execDir); + if (!loopDir) + loopDir = findNestedOMPLoopDirective(execDir); + if (loopDir && !getSupportedLoopForStmt(cgf, *loopDir)) + return mlir::failure(); + } + + std::optional<CIRGenFunction::OMPHostEvalBounds> hostEval; + if (isSPMD && !cgf.getCIRGenModule().getLangOpts().OpenMPIsTargetDevice) { + if (!loopDir || !(hostEval = emitHostEvalLoopBounds(cgf, *loopDir))) { + cgf.getCIRGenModule().errorNYI( + s.getSourceRange(), "OpenMP target host-evaluated loop bounds"); + return mlir::failure(); + } + clauseOps.hostEvalVars.push_back(hostEval->zero); + clauseOps.hostEvalVars.push_back(hostEval->tripCount); + clauseOps.hostEvalVars.push_back(hostEval->one); + } + clauseOps.kernelType = mlir::omp::TargetExecModeAttr::get( - &cgf.getMLIRContext(), mlir::omp::TargetExecMode::generic); + &cgf.getMLIRContext(), isSPMD ? mlir::omp::TargetExecMode::spmd + : mlir::omp::TargetExecMode::generic); auto targetOp = mlir::omp::TargetOp::create(builder, begin, clauseOps); - if (!omp::isLastItemInQueue(item, queue)) + if (!omp::isLastItemInQueue(item, queue) || hasCombinableNestedLeaf(execDir)) targetOp.setCombined(true); + // Block arguments must be added in the order BlockArgOpenMPOpInterface + // expects: host_eval arguments precede map arguments. mlir::Block &block = targetOp.getRegion().emplaceBlock(); + for (mlir::Value hostEvalVar : clauseOps.hostEvalVars) + block.addArgument(hostEvalVar.getType(), begin); for (mlir::Value mapVar : clauseOps.mapVars) block.addArgument(mapVar.getType(), begin); + auto argIface = mlir::cast<mlir::omp::BlockArgOpenMPOpInterface>(*targetOp); + llvm::MutableArrayRef<mlir::BlockArgument> mapBlockArgs = + argIface.getMapBlockArgs(); llvm::SmallVector<std::pair<const VarDecl *, Address>> savedAddrs; for (auto [idx, vd] : llvm::enumerate(mapSyms)) { Address origAddr = cgf.getAddrOfLocalVar(vd); savedAddrs.push_back({vd, origAddr}); - mlir::Value blockArg = block.getArgument(idx); - cgf.replaceAddrOfLocalVar(vd, Address(blockArg, origAddr.getAlignment())); + cgf.replaceAddrOfLocalVar( + vd, Address(mapBlockArgs[idx], origAddr.getAlignment())); + } + + // Forward the host_eval block arguments to the nested loop's emission. + std::optional<CIRGenFunction::OMPHostEvalBounds> newHostEvalBounds; + if (hostEval) { + llvm::MutableArrayRef<mlir::BlockArgument> hostEvalBlockArgs = + argIface.getHostEvalBlockArgs(); + newHostEvalBounds = CIRGenFunction::OMPHostEvalBounds{ + hostEvalBlockArgs[0], hostEvalBlockArgs[1], hostEvalBlockArgs[2], + /*applied=*/false}; } + CIRGenFunction::OMPHostEvalBoundsRAII hostEvalGuard( + cgf, std::move(newHostEvalBounds)); mlir::LogicalResult res = emitOMPRegionBody<mlir::omp::TerminatorOp>( cgf, block, begin, end, emitBody); diff --git a/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c b/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c index 1cf0ecd315e0d1..b7d32d801f4ce0 100644 --- a/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c +++ b/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c @@ -39,6 +39,15 @@ void loop_continue(int *a) { a[i] = i; } + // Diagnosed before the SPMD omp.target is created, so no target is left + // behind without its omp.loop_nest. + int s = 0; +#pragma omp target parallel for map(tofrom: s) + for (int i = 0; i < 10; ++i) { + // expected-error@+1{{ClangIR code gen Not Yet Implemented: continue in an OpenMP loop body}} + if (i == 3) continue; + } + // A continue that targets a loop nested in the body is supported. #pragma omp for for (int i = 0; i < 10; ++i) { diff --git a/clang/test/CIR/CodeGenOpenMP/target-host-eval.c b/clang/test/CIR/CodeGenOpenMP/target-host-eval.c new file mode 100644 index 00000000000000..edbfa75139f362 --- /dev/null +++ b/clang/test/CIR/CodeGenOpenMP/target-host-eval.c @@ -0,0 +1,96 @@ +// REQUIRES: amdgpu-registered-target + +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fopenmp \ +// RUN: -fopenmp-targets=amdgcn-amd-amdhsa -emit-cir -fclangir %s -o - \ +// RUN: | FileCheck %s --check-prefix=CIR-HOST +// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fopenmp -fopenmp-is-target-device \ +// RUN: -emit-cir -fclangir %s -o - \ +// RUN: | FileCheck %s --check-prefix=CIR-DEVICE + +// Both sides must also translate to LLVM IR. +// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fopenmp \ +// RUN: -fopenmp-targets=amdgcn-amd-amdhsa -fclangir -emit-llvm-bc %s -o %t-host.bc +// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fopenmp -fopenmp-is-target-device \ +// RUN: -fopenmp-host-ir-file-path %t-host.bc -fclangir -emit-llvm %s -o /dev/null + +int getLB(void); +int getStep(void); +void work(int); + +// The lower bound is stored in a Sema-generated `.capture_expr.` variable. +// The host evaluates it to compute the trip count for host_eval, and the loop +// inside the omp.target evaluates it again into its own copy, since the +// induction variable update can't use the host's copy across the isolated +// region. Classic codegen also evaluates it on both sides. +void dynamic_lb() { +#pragma omp target +#pragma omp parallel +#pragma omp for + for (int i = getLB(); i < 10; ++i) + work(i); +} + +// CIR-HOST-LABEL: cir.func{{.*}}@dynamic_lb +// CIR-HOST: %[[HOST_LB:.*]] = cir.alloca ".capture_expr." align(4) init : !cir.ptr<!s32i> +// CIR-HOST: %[[HOST_LB_VAL:.*]] = cir.call @getLB() +// CIR-HOST-NEXT: cir.store align(4) %[[HOST_LB_VAL]], %[[HOST_LB]] +// CIR-HOST: %[[TRIPCOUNT_SEL:.*]] = cir.select if +// CIR-HOST: %[[TRIPCOUNT:.*]] = cir.builtin_int_cast %[[TRIPCOUNT_SEL]] : !u32i -> i32 +// CIR-HOST: omp.target kernel_type(spmd) host_eval(%{{.*}} -> %[[AZERO:.*]], %[[TRIPCOUNT]] -> %[[ATRIPCOUNT:.*]], %{{.*}} -> %[[AONE:.*]] : i32, i32, i32) { +// CIR-HOST-NEXT: omp.parallel { +// CIR-HOST-NEXT: %[[LB:.*]] = cir.alloca ".capture_expr." align(4) init : !cir.ptr<!s32i> +// CIR-HOST: %[[LB_VAL:.*]] = cir.call @getLB() +// CIR-HOST-NEXT: cir.store align(4) %[[LB_VAL]], %[[LB]] +// CIR-HOST: omp.loop_nest (%{{.*}}) : i32 = (%[[AZERO]]) to (%[[ATRIPCOUNT]]) step (%[[AONE]]) { +// CIR-HOST: cir.load align(4) %[[LB]] : !cir.ptr<!s32i>, !s32i +// CIR-HOST: cir.call @work( + +// CIR-DEVICE-LABEL: cir.func{{.*}}@dynamic_lb +// CIR-DEVICE: omp.target kernel_type(spmd) { +// CIR-DEVICE: cir.call @getLB() +// CIR-DEVICE: omp.loop_nest + +// A non-constant step is likewise stored in a `.new_step` variable that both +// the trip count and the induction variable update read. +void dynamic_step() { +#pragma omp target parallel for + for (int i = 0; i < 10; i += getStep()) + work(i); +} + +// CIR-HOST-LABEL: cir.func{{.*}}@dynamic_step +// CIR-HOST: %[[HOST_STEP:.*]] = cir.alloca ".new_step" align(4) init : !cir.ptr<!s32i> +// CIR-HOST: %[[HOST_STEP_VAL:.*]] = cir.call @getStep() +// CIR-HOST-NEXT: cir.store align(4) %[[HOST_STEP_VAL]], %[[HOST_STEP]] +// CIR-HOST: omp.target kernel_type(spmd) host_eval(%{{.*}} -> %[[AZERO:.*]], %{{.*}} -> %[[ATRIPCOUNT:.*]], %{{.*}} -> %[[AONE:.*]] : i32, i32, i32) { +// CIR-HOST-NEXT: omp.parallel { +// CIR-HOST-NEXT: %[[STEP:.*]] = cir.alloca ".new_step" align(4) init : !cir.ptr<!s32i> +// CIR-HOST: %[[STEP_VAL:.*]] = cir.call @getStep() +// CIR-HOST-NEXT: cir.store align(4) %[[STEP_VAL]], %[[STEP]] +// CIR-HOST: omp.loop_nest (%{{.*}}) : i32 = (%[[AZERO]]) to (%[[ATRIPCOUNT]]) step (%[[AONE]]) { +// CIR-HOST: cir.load align(4) %[[STEP]] : !cir.ptr<!s32i>, !s32i +// CIR-HOST: cir.call @work( + +// CIR-DEVICE-LABEL: cir.func{{.*}}@dynamic_step +// CIR-DEVICE: omp.target kernel_type(spmd) { +// CIR-DEVICE: cir.call @getStep() +// CIR-DEVICE: omp.loop_nest + +// A parallel region without a worksharing loop isn't a target SPMD +// construct, so the omp.target is a generic kernel without host_eval, just +// like the combined `target parallel`. +void parallel_without_loop() { +#pragma omp target +#pragma omp parallel + { work(0); } +} + +// CIR-HOST-LABEL: cir.func{{.*}}@parallel_without_loop +// CIR-HOST-NEXT: omp.target kernel_type(generic) { +// CIR-HOST-NEXT: omp.parallel { +// CIR-HOST: cir.call @work( + +// CIR-DEVICE-LABEL: cir.func{{.*}}@parallel_without_loop +// CIR-DEVICE-NEXT: omp.target kernel_type(generic) { +// CIR-DEVICE-NEXT: omp.parallel { +// CIR-DEVICE: cir.call @work( diff --git a/clang/test/CIR/CodeGenOpenMP/target-parallel-for.c b/clang/test/CIR/CodeGenOpenMP/target-parallel-for.c index 46ec99b09482ff..9a877d160f220f 100644 --- a/clang/test/CIR/CodeGenOpenMP/target-parallel-for.c +++ b/clang/test/CIR/CodeGenOpenMP/target-parallel-for.c @@ -22,8 +22,7 @@ // RUN: | FileCheck %s --check-prefixes=LLVM-HOST,LLVM-HOST-OGCG // Device-side lowering to LLVM IR: compiled in two steps to mirror the -// offloading driver. The kernel entry sequence is the same on both paths, -// aside from the wrapper-vs-null difference seen in target-parallel.c. +// offloading driver. The kernel entry sequence is the same on both paths. // Past that point, CIR and OGCG lower the worksharing loop through // different runtime APIs, so they're checked separately under // LLVM-DEVICE-CIR/LLVM-DEVICE-OGCG. @@ -42,6 +41,8 @@ void during(int); +// This is a target SPMD construct, so the host also computes the loop's +// trip count and forwards it via host_eval block arguments. void target_parallel_for() { #pragma omp target #pragma omp parallel @@ -52,18 +53,15 @@ void target_parallel_for() { } // CIR-HOST: cir.func{{.*}}@target_parallel_for -// CIR-HOST: omp.target kernel_type(generic) { -// CIR-HOST: omp.parallel { - -// CIR-HOST: %[[IV_ALLOCA:.*]] = cir.alloca ".omp.iv" align(4) : !cir.ptr<!s32i> -// CIR-HOST: %[[I_ALLOCA:.*]] = cir.alloca "i" align(4) : !cir.ptr<!s32i> // The loop only runs if its precondition `0 < 10` holds. -// CIR-HOST-NEXT: %[[PRE_L:.*]] = cir.const #cir.int<0> : !s32i +// CIR-HOST: %[[PRE_L:.*]] = cir.const #cir.int<0> : !s32i // CIR-HOST-NEXT: %[[PRE_R:.*]] = cir.const #cir.int<10> : !s32i // CIR-HOST-NEXT: %[[PRECOND:.*]] = cir.cmp lt %[[PRE_L]], %[[PRE_R]] : !s32i -// The loop bounds are normalized to a `[0, tripCount)` range, with -// tripCount = (10 - (0 - 1 + 1)) / 1 = 10. +// The trip count is computed before the omp.target, from the original +// bounds/step: tripCount = (10 - (0 - 1 + 1)) / 1 = 10. Then 0, the trip +// count, and 1 are each cast to a builtin integer and forwarded as the +// omp.target's host_eval operands. // CIR-HOST-NEXT: %[[HI:.*]] = cir.const #cir.int<10> : !s32i // CIR-HOST-NEXT: %[[LO:.*]] = cir.const #cir.int<0> : !s32i // CIR-HOST-NEXT: %[[STEP_A:.*]] = cir.const #cir.int<1> : !s32i @@ -75,14 +73,21 @@ void target_parallel_for() { // CIR-HOST-NEXT: %[[TRIPCOUNT_CIR:.*]] = cir.div %[[SPAN]], %[[STEP_B]] : !s32i // CIR-HOST-NEXT: %[[TC_ZERO:.*]] = cir.const #cir.int<0> : !s32i // CIR-HOST-NEXT: %[[TRIPCOUNT_SEL:.*]] = cir.select if %[[PRECOND]] then %[[TRIPCOUNT_CIR]] else %[[TC_ZERO]] : (!cir.bool, !s32i, !s32i) -> !s32i -// CIR-HOST: %[[ZERO_CIR:.*]] = cir.const #cir.int<0> : !s32i -// CIR-HOST: %[[ZERO:.*]] = cir.builtin_int_cast %[[ZERO_CIR]] : !s32i -> i32 -// CIR-HOST: %[[ONE_CIR:.*]] = cir.const #cir.int<1> : !s32i -// CIR-HOST: %[[ONE:.*]] = cir.builtin_int_cast %[[ONE_CIR]] : !s32i -> i32 -// CIR-HOST: %[[TRIPCOUNT:.*]] = cir.builtin_int_cast %[[TRIPCOUNT_SEL]] : !s32i -> i32 +// CIR-HOST-NEXT: %[[ZERO_CIR:.*]] = cir.const #cir.int<0> : !s32i +// CIR-HOST-NEXT: %[[ZERO:.*]] = cir.builtin_int_cast %[[ZERO_CIR]] : !s32i -> i32 +// CIR-HOST-NEXT: %[[TRIPCOUNT:.*]] = cir.builtin_int_cast %[[TRIPCOUNT_SEL]] : !s32i -> i32 +// CIR-HOST-NEXT: %[[ONE_CIR:.*]] = cir.const #cir.int<1> : !s32i +// CIR-HOST-NEXT: %[[ONE:.*]] = cir.builtin_int_cast %[[ONE_CIR]] : !s32i -> i32 +// CIR-HOST-NEXT: omp.target kernel_type(spmd) host_eval(%[[ZERO]] -> %[[AZERO:.*]], %[[TRIPCOUNT]] -> %[[ATRIPCOUNT:.*]], %[[ONE]] -> %[[AONE:.*]] : i32, i32, i32) { +// CIR-HOST-NEXT: omp.parallel { + +// CIR-HOST: %[[IV_ALLOCA:.*]] = cir.alloca ".omp.iv" align(4) : !cir.ptr<!s32i> +// CIR-HOST: %[[I_ALLOCA:.*]] = cir.alloca "i" align(4) : !cir.ptr<!s32i> -// CIR-HOST: omp.wsloop private(@{{.*}} %[[I_ALLOCA]] -> %[[I_PRIV:.*]] : !cir.ptr<!s32i>) { -// CIR-HOST-NEXT: omp.loop_nest (%[[IV:.*]]) : i32 = (%[[ZERO]]) to (%[[TRIPCOUNT]]) step (%[[ONE]]) { +// The loop inside the target region uses the host_eval block arguments +// instead of recomputing the bounds. +// CIR-HOST-NEXT: omp.wsloop private(@{{.*}} %[[I_ALLOCA]] -> %[[I_PRIV:.*]] : !cir.ptr<!s32i>) { +// CIR-HOST-NEXT: omp.loop_nest (%[[IV:.*]]) : i32 = (%[[AZERO]]) to (%[[ATRIPCOUNT]]) step (%[[AONE]]) { // CIR-HOST: %[[IV_CIR:.*]] = cir.builtin_int_cast %[[IV]] : i32 -> !s32i // CIR-HOST: cir.store align(4) %[[IV_CIR]], %[[IV_ALLOCA]] : !s32i, !cir.ptr<!s32i> // CIR-HOST: cir.store align(4) %{{.*}}, %[[I_PRIV]] : !s32i, !cir.ptr<!s32i> @@ -95,7 +100,7 @@ void target_parallel_for() { // CIR-HOST: } // CIR-DEVICE: cir.func{{.*}}@target_parallel_for -// CIR-DEVICE: omp.target kernel_type(generic) { +// CIR-DEVICE: omp.target kernel_type(spmd) { // CIR-DEVICE: omp.parallel { // The two allocas and their address-space casts can be emitted in either @@ -110,7 +115,8 @@ void target_parallel_for() { // CIR-DEVICE: %[[PRE_L:.*]] = cir.const #cir.int<0> : !s32i // CIR-DEVICE-NEXT: %[[PRE_R:.*]] = cir.const #cir.int<10> : !s32i // CIR-DEVICE-NEXT: %[[PRECOND:.*]] = cir.cmp lt %[[PRE_L]], %[[PRE_R]] : !s32i -// Same trip count computation as on the host. +// The device has no host_eval operands, so it recomputes the same trip +// count inside the region. // CIR-DEVICE-NEXT: %[[HI:.*]] = cir.const #cir.int<10> : !s32i // CIR-DEVICE-NEXT: %[[LO:.*]] = cir.const #cir.int<0> : !s32i // CIR-DEVICE-NEXT: %[[STEP_A:.*]] = cir.const #cir.int<1> : !s32i @@ -144,7 +150,9 @@ void target_parallel_for() { // The combined `target parallel for` directive decomposes into `target`, // `parallel` and `for` leaves and lowers to the same nesting as the explicit // target/parallel/for above: an omp.wsloop + omp.loop_nest inside omp.parallel -// inside omp.target. +// inside omp.target. This is a target SPMD construct, so the omp.target is +// marked kernel_type(spmd) with host_eval'd loop bounds, just like the +// explicitly nested directives above. void combined_target_parallel_for() { #pragma omp target parallel for for (int i = 0; i < 10; i++) { @@ -153,11 +161,8 @@ void combined_target_parallel_for() { } // CIR-HOST: cir.func{{.*}}@combined_target_parallel_for -// CIR-HOST: omp.target kernel_type(generic) { -// CIR-HOST: omp.parallel { -// CIR-HOST: %[[CI_ALLOCA:.*]] = cir.alloca "i" align(4) : !cir.ptr<!s32i> // The loop only runs if its precondition `0 < 10` holds. -// CIR-HOST-NEXT: %[[PRE_L:.*]] = cir.const #cir.int<0> : !s32i +// CIR-HOST: %[[PRE_L:.*]] = cir.const #cir.int<0> : !s32i // CIR-HOST-NEXT: %[[PRE_R:.*]] = cir.const #cir.int<10> : !s32i // CIR-HOST-NEXT: %[[PRECOND:.*]] = cir.cmp lt %[[PRE_L]], %[[PRE_R]] : !s32i // tripCount = (10 - (0 - 1 + 1)) / 1 = 10 @@ -173,8 +178,11 @@ void combined_target_parallel_for() { // CIR-HOST-NEXT: %[[TC_ZERO:.*]] = cir.const #cir.int<0> : !s32i // CIR-HOST-NEXT: %[[TRIPCOUNT_SEL:.*]] = cir.select if %[[PRECOND]] then %[[TRIPCOUNT_CIR]] else %[[TC_ZERO]] : (!cir.bool, !s32i, !s32i) -> !s32i // CIR-HOST: %[[TRIPCOUNT:.*]] = cir.builtin_int_cast %[[TRIPCOUNT_SEL]] : !s32i -> i32 +// CIR-HOST: omp.target kernel_type(spmd) host_eval(%{{.*}} -> %[[AZERO:.*]], %[[TRIPCOUNT]] -> %[[ATRIPCOUNT:.*]], %{{.*}} -> %[[AONE:.*]] : i32, i32, i32) { +// CIR-HOST: omp.parallel { +// CIR-HOST: %[[CI_ALLOCA:.*]] = cir.alloca "i" align(4) : !cir.ptr<!s32i> // CIR-HOST: omp.wsloop private(@{{.*}} %[[CI_ALLOCA]] -> %{{.*}} : !cir.ptr<!s32i>) { -// CIR-HOST-NEXT: omp.loop_nest (%[[CIV:.*]]) : i32 = (%{{.*}}) to (%[[TRIPCOUNT]]) step (%{{.*}}) { +// CIR-HOST-NEXT: omp.loop_nest (%[[CIV:.*]]) : i32 = (%[[AZERO]]) to (%[[ATRIPCOUNT]]) step (%[[AONE]]) { // CIR-HOST: cir.call @{{.*}}during // CIR-HOST: omp.yield // CIR-HOST: } @@ -185,7 +193,7 @@ void combined_target_parallel_for() { // CIR-HOST: } {omp.combined} // CIR-DEVICE: cir.func{{.*}}@combined_target_parallel_for -// CIR-DEVICE: omp.target kernel_type(generic) { +// CIR-DEVICE: omp.target kernel_type(spmd) { // CIR-DEVICE: omp.parallel { // The loop only runs if its precondition `0 < 10` holds. // CIR-DEVICE: %[[PRE_L:.*]] = cir.const #cir.int<0> : !s32i @@ -217,9 +225,16 @@ void combined_target_parallel_for() { // Host wrappers: the __tgt_target_kernel call, the offload-failed fallback // branch, and the call into the offloading-entry function are identical on -// both paths. +// both paths. This is a target SPMD construct, so CIR's kernel-launch +// arguments carry the host_eval'd trip count (10) in the trip count field +// (index 8); OGCG doesn't forward a host-computed trip count here, so it +// leaves that field 0. // // LLVM-HOST-LABEL: define {{.*}} void @target_parallel_for( +// LLVM-HOST: %[[KARGS:.*]] = alloca %struct.__tgt_kernel_arguments, align 8 +// LLVM-HOST: %[[TRIPCOUNT_GEP:.*]] = getelementptr inbounds nuw %struct.__tgt_kernel_arguments, ptr %[[KARGS]], i32 0, i32 8 +// LLVM-HOST-CIR-NEXT: store i64 10, ptr %[[TRIPCOUNT_GEP]], align 8 +// LLVM-HOST-OGCG-NEXT: store i64 0, ptr %[[TRIPCOUNT_GEP]], align 8 // LLVM-HOST: call i32 @__tgt_target_kernel( // LLVM-HOST: br i1 %{{.*}}, label %[[FAILED:[^,]+]], label %{{.*}} // LLVM-HOST: {{^}}[[FAILED]]: @@ -232,6 +247,9 @@ void combined_target_parallel_for() { // checks are the same either way, just placed where each path actually // emits them (compare the LLVM-HOST-OGCG copy of this block further down). // LLVM-HOST-CIR-LABEL: define {{.*}} void @combined_target_parallel_for( +// LLVM-HOST-CIR: %[[KARGS2:.*]] = alloca %struct.__tgt_kernel_arguments, align 8 +// LLVM-HOST-CIR: %[[TRIPCOUNT_GEP2:.*]] = getelementptr inbounds nuw %struct.__tgt_kernel_arguments, ptr %[[KARGS2]], i32 0, i32 8 +// LLVM-HOST-CIR-NEXT: store i64 10, ptr %[[TRIPCOUNT_GEP2]], align 8 // LLVM-HOST-CIR: call i32 @__tgt_target_kernel( // LLVM-HOST-CIR: br i1 %{{.*}}, label %[[FAILED2:[^,]+]], label %{{.*}} // LLVM-HOST-CIR: {{^}}[[FAILED2]]: @@ -290,6 +308,9 @@ void combined_target_parallel_for() { // content to the LLVM-HOST-CIR block above, just emitted after // target_parallel_for's entry+outlined functions instead of before them. // LLVM-HOST-OGCG-LABEL: define {{.*}} void @combined_target_parallel_for( +// LLVM-HOST-OGCG: %[[KARGS2:.*]] = alloca %struct.__tgt_kernel_arguments, align 8 +// LLVM-HOST-OGCG: %[[TRIPCOUNT_GEP2:.*]] = getelementptr inbounds nuw %struct.__tgt_kernel_arguments, ptr %[[KARGS2]], i32 0, i32 8 +// LLVM-HOST-OGCG-NEXT: store i64 0, ptr %[[TRIPCOUNT_GEP2]], align 8 // LLVM-HOST-OGCG: call i32 @__tgt_target_kernel( // LLVM-HOST-OGCG: br i1 %{{.*}}, label %[[FAILED2:[^,]+]], label %{{.*}} // LLVM-HOST-OGCG: {{^}}[[FAILED2]]: @@ -352,10 +373,10 @@ void combined_target_parallel_for() { // LLVM-DEVICE: br i1 %{{.*}}, label %[[USER_CODE:[^,]+]], label %{{.*}} // LLVM-DEVICE: {{^}}[[USER_CODE]]: -// CIR passes a wrapper function to __kmpc_parallel_60; OGCG passes null -// instead, since it doesn't need one here (same as target-parallel.c). -// LLVM-DEVICE-CIR: call void @__kmpc_parallel_60(ptr {{.*}}, i32 {{.*}}, i32 1, i32 -1, i32 -1, ptr @[[DEV_OUTLINED:[^,]+]], ptr @{{[^,]+}}, ptr {{.*}}, i64 0, i32 0) -// LLVM-DEVICE-OGCG: call void @__kmpc_parallel_60(ptr {{.*}}, i32 {{.*}}, i32 1, i32 -1, i32 -1, ptr @[[DEV_OUTLINED:[^,]+]], ptr null, ptr {{.*}}, i64 0, i32 0) +// Unlike target-parallel.c's generic kernel, this is an SPMD kernel, so +// neither path needs a wrapper here: CIR also passes null, since every +// thread already runs the parallel region directly. +// LLVM-DEVICE: call void @__kmpc_parallel_60(ptr {{.*}}, i32 {{.*}}, i32 1, i32 -1, i32 -1, ptr @[[DEV_OUTLINED:[^,]+]], ptr null, ptr {{.*}}, i64 0, i32 0) // LLVM-DEVICE: call void @__kmpc_target_deinit() @@ -381,8 +402,7 @@ void combined_target_parallel_for() { // LLVM-DEVICE: br i1 %{{.*}}, label %[[USER_CODE2:[^,]+]], label %{{.*}} // LLVM-DEVICE: {{^}}[[USER_CODE2]]: -// LLVM-DEVICE-CIR: call void @__kmpc_parallel_60(ptr {{.*}}, i32 {{.*}}, i32 1, i32 -1, i32 -1, ptr @[[DEV_OUTLINED2:[^,]+]], ptr @{{[^,]+}}, ptr {{.*}}, i64 0, i32 0) -// LLVM-DEVICE-OGCG: call void @__kmpc_parallel_60(ptr {{.*}}, i32 {{.*}}, i32 1, i32 -1, i32 -1, ptr @[[DEV_OUTLINED2:[^,]+]], ptr null, ptr {{.*}}, i64 0, i32 0) +// LLVM-DEVICE: call void @__kmpc_parallel_60(ptr {{.*}}, i32 {{.*}}, i32 1, i32 -1, i32 -1, ptr @[[DEV_OUTLINED2:[^,]+]], ptr null, ptr {{.*}}, i64 0, i32 0) // LLVM-DEVICE: call void @__kmpc_target_deinit() _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
