[clang] [CIR][OpenMP] Support the 'collapse' clause on 'for' (PR #248125)
via cfe-commits
cfe-commits at lists.llvm.org
Wed Dec 2 08:57:36 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
@llvm/pr-subscribers-clangir
Author: Arseniy Obolenskiy (aobolensk)
<details>
<summary>Changes</summary>
---
Full diff: https://github.com/llvm/llvm-project/pull/248125.diff
5 Files Affected:
- (modified) clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp (+60-34)
- (modified) clang/test/CIR/CodeGenOpenMP/for-loop-forms.c (+44)
- (modified) clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c (+30)
- (modified) clang/test/CIR/CodeGenOpenMP/not-yet-implemented.cpp (+9)
- (modified) clang/test/CIR/CodeGenOpenMP/target-host-eval.c (+22)
``````````diff
diff --git a/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp b/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp
index a634f0ea297b4..a905b9a30afdb 100644
--- a/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp
@@ -260,10 +260,23 @@ static mlir::LogicalResult emitLoopPreInit(CIRGenFunction &cgf,
/// Emits the Sema-generated pre-init statements for an OpenMP loop directive.
static mlir::LogicalResult emitLoopPreInits(CIRGenFunction &cgf,
- const Stmt *preInits) {
+ const OMPLoopDirective &s) {
+ const Stmt *preInits = s.getPreInits();
if (!preInits)
return mlir::success();
+ // Pre-inits may read a counter, e.g. an inner step using an outer one.
+ llvm::SmallVector<CIRGenFunction::DeclMapRevertingRAII, 4> counterShadows;
+ counterShadows.reserve(s.counters().size());
+ for (const Expr *counter : s.counters()) {
+ const auto *vd = cast<VarDecl>(cast<DeclRefExpr>(counter)->getDecl());
+ counterShadows.emplace_back(cgf, vd);
+ Address tmp = cgf.createMemTemp(vd->getType().getNonReferenceType(),
+ cgf.getLoc(s.getBeginLoc()));
+ cgf.replaceAddrOfLocalVar(vd, tmp);
+ cgf.symbolTable.insert(vd, tmp.getPointer());
+ }
+
if (const auto *compound = dyn_cast<CompoundStmt>(preInits)) {
for (const Stmt *stmt : compound->body())
if (emitLoopPreInit(cgf, stmt).failed())
@@ -307,14 +320,16 @@ static const ContinueStmt *findLoopBodyContinue(const Stmt *s) {
}
/// Emits an omp.loop_nest that iterates a normalized `[0, tripCount)` range
-/// and recomputes the real induction variable each iteration using the given
-/// update expression.
-static mlir::LogicalResult
-emitOMPLoopNest(CIRGenFunction &cgf, const ForStmt &forStmt, mlir::Value lb,
- mlir::Value ub, mlir::Value step, const VarDecl *ivDecl,
- const Expr *update) {
+/// and recomputes the real induction variables each iteration using the
+/// update expressions of \p s.
+static mlir::LogicalResult emitOMPLoopNest(CIRGenFunction &cgf,
+ const OMPLoopDirective &s,
+ const Stmt *body, mlir::Value lb,
+ mlir::Value ub, mlir::Value step,
+ const VarDecl *ivDecl) {
CIRGenBuilderTy &builder = cgf.getBuilder();
- mlir::Location loc = cgf.getLoc(forStmt.getSourceRange());
+ const Stmt *loop = s.getInnermostCapturedStmt()->getCapturedStmt();
+ mlir::Location loc = cgf.getLoc(loop->getSourceRange());
auto loopNestOp = mlir::omp::LoopNestOp::create(
builder, loc, /*collapse_num_loops=*/1, lb, ub, step,
@@ -323,38 +338,36 @@ emitOMPLoopNest(CIRGenFunction &cgf, const ForStmt &forStmt, mlir::Value lb,
block.addArgument(lb.getType(), loc);
return emitOMPRegionBody<mlir::omp::YieldOp>(
- cgf, block, loc, cgf.getLoc(forStmt.getEndLoc()),
+ cgf, block, loc, cgf.getLoc(loop->getEndLoc()),
[&]() -> mlir::LogicalResult {
// Store the normalized counter block argument into the normalized
- // loop variable's storage location, then let Sema's update expression
- // recompute the real induction variable from it.
+ // loop variable's storage location, then let the Sema update
+ // expressions recompute the real induction variables from it.
mlir::Value iv = block.getArgument(0);
Address ivAddr = cgf.getAddrOfLocalVar(ivDecl);
mlir::Value civVal =
builder.createBuiltinIntCast(loc, iv, ivAddr.getElementType());
builder.createStore(loc, civVal, ivAddr);
- cgf.emitIgnoredExpr(update);
-
- if (!forStmt.getBody())
- return mlir::success();
- return cgf.emitStmt(forStmt.getBody(), /*useCurrentScope=*/true);
+ for (const Expr *update : s.updates())
+ cgf.emitIgnoredExpr(update);
+ return cgf.emitStmt(body, /*useCurrentScope=*/true);
});
}
-/// Evaluates the clauses allowed on the `for` directive; none are supported
-/// yet, so every eligible clause is reported as NYI.
+/// Evaluates the clauses allowed on the `for` directive, reporting the
+/// unsupported ones as NYI.
static mlir::LogicalResult
emitWsloopClauses(CIRGenFunction &cgf, CIRGenModule &cgm,
CIRGenBuilderTy &builder, mlir::Location loc,
llvm::ArrayRef<const OMPClause *> clauses,
mlir::omp::WsloopOperands &clauseOps) {
OpenMPClauseEmitter ce(cgf, cgm, builder, loc, clauses);
- return ce.emitNYI</*supported=*/>(
+ // Sema folds collapsed loops into one iteration space.
+ return ce.emitNYI</*supported=*/OMPCollapseClause>(
/*nyi=*/OpenMPNYIClauseList<
- OMPAllocateClause, OMPCollapseClause, OMPFirstprivateClause,
- OMPLastprivateClause, OMPLinearClause, OMPNowaitClause,
- OMPOrderClause, OMPOrderedClause, OMPPrivateClause,
- OMPReductionClause, OMPScheduleClause>{},
+ OMPAllocateClause, OMPFirstprivateClause, OMPLastprivateClause,
+ OMPLinearClause, OMPNowaitClause, OMPOrderClause, OMPOrderedClause,
+ OMPPrivateClause, OMPReductionClause, OMPScheduleClause>{},
llvm::omp::Directive::OMPD_for);
}
@@ -402,20 +415,33 @@ 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.
+/// Returns the innermost `for` loop associated with \p s, or reports NYI and
+/// returns null if the loop nest 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);
+ for (unsigned level = 1; forStmt && level < s.getLoopsNumber(); ++level) {
+ loopStmt = forStmt->getBody()->IgnoreContainers();
+ 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");
+ isa<CXXForRangeStmt>(loopStmt)
+ ? "range-based for loop in an OpenMP loop directive"
+ : isa<OMPCanonicalLoop>(loopStmt)
+ ? "OpenMP OMPCanonicalLoop"
+ : "OpenMP loop nest with intervening code or a loop "
+ "transformation");
+ return nullptr;
+ }
+
+ // Set only by non-rectangular nests, as tiles are rejected above.
+ if (llvm::any_of(s.finals_conditions(), [](const Expr *e) { return e; })) {
+ cgm.errorNYI(s.getSourceRange(), "non-rectangular OpenMP loop nest");
return nullptr;
}
@@ -482,7 +508,7 @@ emitHostEvalLoopBounds(CIRGenFunction &cgf, const OMPLoopDirective &s) {
preInitShadows.emplace_back(cgf, vd);
CIRGenFunction::SymTableScopeTy preInitScope(cgf.symbolTable);
- if (emitLoopPreInits(cgf, s.getPreInits()).failed())
+ if (emitLoopPreInits(cgf, s).failed())
return std::nullopt;
CIRGenBuilderTy &builder = cgf.getBuilder();
mlir::Location loc = cgf.getLoc(s.getBeginLoc());
@@ -518,7 +544,7 @@ emitOMPWorksharingLoop(CIRGenFunction &cgf, const OMPLoopDirective &s,
if (!forStmt)
return mlir::failure();
- if (emitLoopPreInits(cgf, s.getPreInits()).failed())
+ if (emitLoopPreInits(cgf, s).failed())
return mlir::failure();
// True when the enclosing omp.target already computed this loop's trip
@@ -586,8 +612,8 @@ emitOMPWorksharingLoop(CIRGenFunction &cgf, const OMPLoopDirective &s,
cgf.symbolTable.insert(vd, privAddr.getPointer());
}
- return emitOMPLoopNest(cgf, *forStmt, zero, tripCount, one, ivDecl,
- s.updates()[0]);
+ return emitOMPLoopNest(cgf, s, forStmt->getBody(), zero, tripCount, one,
+ ivDecl);
}
mlir::LogicalResult
diff --git a/clang/test/CIR/CodeGenOpenMP/for-loop-forms.c b/clang/test/CIR/CodeGenOpenMP/for-loop-forms.c
index ab231fd94a97e..8bff78b9a197f 100644
--- a/clang/test/CIR/CodeGenOpenMP/for-loop-forms.c
+++ b/clang/test/CIR/CodeGenOpenMP/for-loop-forms.c
@@ -423,3 +423,47 @@ void unsigned_false_precond() {
// CIR: omp.wsloop private(@{{.*}} %[[I_ALLOCA]] -> %{{.*}} : !cir.ptr<!u32i>) {
// CIR-NEXT: omp.loop_nest (%{{.*}}) : i32 = (%{{.*}}) to (%[[TRIPCOUNT]]) step (%{{.*}}) {
}
+
+void collapse_two_loops() {
+ // CIR: cir.func{{.*}}@{{.*}}collapse_two_loops
+#pragma omp for collapse(2)
+ for (int i = 0; i < 4; i++) {
+ for (int j = 0; j < 8; j++) {
+ during(j);
+ }
+ }
+ // CIR: %[[IV_ALLOCA:.*]] = cir.alloca ".omp.iv" align(4) : !cir.ptr<!s32i>
+ // CIR-NEXT: %[[I_ALLOCA:.*]] = cir.alloca "i" align(4) : !cir.ptr<!s32i>
+ // CIR-NEXT: %[[J_ALLOCA:.*]] = cir.alloca "j" align(4) : !cir.ptr<!s32i>
+ // CIR: %[[PRECOND:.*]] = cir.ternary
+ // CIR: %[[I_TRIPS:.*]] = cir.div {{.*}} : !s32i
+ // CIR: %[[J_TRIPS:.*]] = cir.div {{.*}} : !s32i
+ // CIR-NEXT: %[[TRIPS:.*]] = cir.mul nsw %[[I_TRIPS]], %[[J_TRIPS]] : !s32i
+ // CIR: %[[TRIPCOUNT_SEL:.*]] = cir.select if %[[PRECOND]] then %[[TRIPS]] else %{{.*}}
+ // CIR: %[[TRIPCOUNT:.*]] = cir.builtin_int_cast %[[TRIPCOUNT_SEL]] : !s32i -> i32
+ // CIR: omp.wsloop private(@{{.*}} %[[I_ALLOCA]] -> %[[I_PRIV:.*]], @{{.*}} %[[J_ALLOCA]] -> %[[J_PRIV:.*]] : !cir.ptr<!s32i>, !cir.ptr<!s32i>) {
+ // CIR-NEXT: omp.loop_nest (%{{.*}}) : i32 = (%{{.*}}) to (%[[TRIPCOUNT]]) step (%{{.*}}) {
+ // CIR: cir.store align(4) %{{.*}}, %[[IV_ALLOCA]]
+ // CIR: %[[IV_I:.*]] = cir.load align(4) %[[IV_ALLOCA]]
+ // CIR: cir.div %[[IV_I]], %{{.*}} : !s32i
+ // CIR: cir.store align(4) %{{.*}}, %[[I_PRIV]]
+ // CIR: %[[IV_J:.*]] = cir.load align(4) %[[IV_ALLOCA]]
+ // CIR: cir.sub nsw %[[IV_J]], %{{.*}} : !s32i
+ // CIR: cir.store align(4) %{{.*}}, %[[J_PRIV]]
+ // CIR-NEXT: %[[J:.*]] = cir.load align(4) %[[J_PRIV]]
+ // CIR-NEXT: cir.call @during(%[[J]])
+ // CIR-NEXT: omp.yield
+}
+
+// The step is captured before the loop, so `i` reads a scratch slot.
+void collapse_step_reads_outer_counter(int n) {
+ // CIR: cir.func{{.*}}@{{.*}}collapse_step_reads_outer_counter
+ // CIR: %[[I_TMP:.*]] = cir.alloca "tmp" align(4) : !cir.ptr<!s32i>
+ // CIR: %[[STEP:.*]] = cir.alloca ".new_step" align(4) init : !cir.ptr<!s32i>
+ // CIR: %[[I_VAL:.*]] = cir.load align(4) %[[I_TMP]] : !cir.ptr<!s32i>, !s32i
+ // CIR-NEXT: cir.store align(4) %[[I_VAL]], %[[STEP]] : !s32i, !cir.ptr<!s32i>
+#pragma omp for collapse(2)
+ for (int i = 1; i < n; ++i)
+ for (int j = 0; j < n; j += i)
+ during(j);
+}
diff --git a/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c b/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c
index 9b5e31eb0a572..5b186f0fd657f 100644
--- a/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c
+++ b/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.c
@@ -61,6 +61,14 @@ void loop_continue(int *a) {
if (i == 3) continue;
}
+#pragma omp for collapse(2)
+ for (int i = 0; i < 10; ++i)
+ for (int j = 0; j < 10; ++j) {
+ // expected-error at +1{{ClangIR code gen Not Yet Implemented: continue in an OpenMP loop body}}
+ if (j == 3) continue;
+ a[j] = i;
+ }
+
// A continue that targets a loop nested in the body is supported.
#pragma omp for
for (int i = 0; i < 10; ++i) {
@@ -70,3 +78,25 @@ void loop_continue(int *a) {
}
}
}
+
+void collapse_nyi(int n, int *a) {
+ // expected-error at +1{{ClangIR code gen Not Yet Implemented: non-rectangular OpenMP loop nest}}
+#pragma omp parallel for collapse(2)
+ for (int i = 0; i < n; ++i)
+ for (int j = i; j < n; ++j)
+ a[j] = i;
+
+#pragma omp parallel for collapse(2)
+ // expected-error at +1{{ClangIR code gen Not Yet Implemented: OpenMP loop nest with intervening code or a loop transformation}}
+ for (int i = 0; i < n; ++i) {
+ a[i] = 0;
+ for (int j = 0; j < n; ++j)
+ a[j] = i;
+ }
+
+#pragma omp for
+ // expected-error at +1{{ClangIR code gen Not Yet Implemented: OpenMP loop nest with intervening code or a loop transformation}}
+#pragma omp tile sizes(2)
+ for (int i = 0; i < n; ++i)
+ a[i] = i;
+}
diff --git a/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.cpp b/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.cpp
index 3e4cece9ebd98..bbc4c9a8d79f6 100644
--- a/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.cpp
+++ b/clang/test/CIR/CodeGenOpenMP/not-yet-implemented.cpp
@@ -7,3 +7,12 @@ void range_for() {
for (int &x : a)
x = 1;
}
+
+void collapse_range_for() {
+ int a[10];
+#pragma omp parallel for collapse(2)
+ for (int i = 0; i < 10; ++i)
+ // expected-error at +1{{ClangIR code gen Not Yet Implemented: range-based for loop in an OpenMP loop directive}}
+ for (int &x : a)
+ x = i;
+}
diff --git a/clang/test/CIR/CodeGenOpenMP/target-host-eval.c b/clang/test/CIR/CodeGenOpenMP/target-host-eval.c
index 4f5a7d28ddf93..5c1588ff3a49b 100644
--- a/clang/test/CIR/CodeGenOpenMP/target-host-eval.c
+++ b/clang/test/CIR/CodeGenOpenMP/target-host-eval.c
@@ -48,6 +48,28 @@ void variable_bounds(int n, int s) {
// CIR-DEVICE: omp.target kernel_type(spmd) map_entries(
// CIR-DEVICE: omp.loop_nest
+// The host computes the step before the loop too, so `i` reads a scratch slot.
+void collapse_step_reads_outer_counter(int n) {
+#pragma omp target map(to: n)
+#pragma omp parallel
+#pragma omp for collapse(2)
+ for (int i = 1; i < n; ++i)
+ for (int j = 0; j < n; j += i)
+ work(j);
+}
+
+// CIR-HOST-LABEL: cir.func{{.*}}@collapse_step_reads_outer_counter
+// CIR-HOST: %[[I_TMP:.*]] = cir.alloca "tmp" align(4) : !cir.ptr<!s32i>
+// CIR-HOST: %[[HOST_STEP:.*]] = cir.alloca ".new_step" align(4) init : !cir.ptr<!s32i>
+// CIR-HOST: %[[I_VAL:.*]] = cir.load align(4) %[[I_TMP]] : !cir.ptr<!s32i>, !s32i
+// CIR-HOST-NEXT: cir.store align(4) %[[I_VAL]], %[[HOST_STEP]]
+// CIR-HOST: omp.target kernel_type(spmd) host_eval(
+// CIR-HOST: omp.loop_nest
+
+// CIR-DEVICE-LABEL: cir.func{{.*}}@collapse_step_reads_outer_counter
+// CIR-DEVICE: omp.target kernel_type(spmd) map_entries(
+// CIR-DEVICE: omp.loop_nest
+
// A bound or step with side effects may evaluate differently on the host than
// in the loop's own context: here, getStep() could return
// omp_get_num_threads(), which is 1 outside the parallel region. A trip count
``````````
</details>
https://github.com/llvm/llvm-project/pull/248125
More information about the cfe-commits
mailing list