https://github.com/jtb20 created 
https://github.com/llvm/llvm-project/pull/242476

At present, in Clang only, OpenMP critical regions are handled for GPU targets 
by executing each lane of a wavefront in sequence.  This patch moves the 
handling to OpenMPIRBuilder so that it works for Flang also, via 
OpenMPIRBuilder::createCritical (fixing a Flang bug in the process). The loop 
now iterates over active lanes rather than all threads in the team.

A helper function, createLaneSerializedRegion, is introduced that is reused by 
subsequent patches in this stack.

This transformation is important for GPUs which execute threads in a group 
(warp or wavefront) in lockstep: an explicit mutex deadlocks in this situation 
when two threads try to claim the mutex at the same time. This patch also 
introduces a property in the per-target OpenMP grid values, named 
omp::GV::GV_Lockstep_Lanes.  Code generation can then query this to generate 
different code, such as this critical region transformation.  For now, this is 
set for all GPU targets: this can be refined later for particular targets, as 
needed.

Tests are added to cover new functionality.

Assisted-By: Claude

>From 6fcb2eabd5534d6f41d4b187bc9d620554b7857f Mon Sep 17 00:00:00 2001
From: Julian Brown <[email protected]>
Date: Fri, 13 Nov 2026 06:25:10 -0600
Subject: [PATCH] [OpenMP] Move critical region serialization to
 OpenMPIRBuilder

At present, in Clang only, OpenMP critical regions are handled for GPU
targets by executing each lane of a wavefront in sequence.  This patch
moves the handling to OpenMPIRBuilder so that it works for Flang also,
via OpenMPIRBuilder::createCritical (fixing a Flang bug in the process).
The loop now iterates over active lanes rather than all threads in
the team.

A helper function, createLaneSerializedRegion, is introduced that is
reused by subsequent patches in this stack.

This transformation is important for GPUs which execute threads in a
group (warp or wavefront) in lockstep: an explicit mutex deadlocks in
this situation when two threads try to claim the mutex at the same time.
This patch also introduces a property in the per-target OpenMP grid
values, named omp::GV::GV_Lockstep_Lanes.  Code generation can then
query this to generate different code, such as this critical region
transformation.  For now, this is set for all GPU targets: this can be
refined later for particular targets, as needed.

Tests are added to cover new functionality.

Assisted-By: Claude
---
 clang/docs/ReleaseNotes.md                    |   4 +
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp      |  92 +++++---------
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.h        |   4 +
 clang/test/OpenMP/nvptx_parallel_codegen.cpp  | 116 +++++++++---------
 .../target_critical_lane_serialization.c      |  29 +++++
 flang/docs/ReleaseNotes.md                    |   3 +
 .../llvm/Frontend/OpenMP/OMPGridValues.h      |  12 ++
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h       |  33 +++++
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp     |  88 +++++++++++++
 .../Frontend/OpenMPIRBuilderTest.cpp          |  70 +++++++++++
 .../Target/LLVMIR/openmp-critical-gpu.mlir    |  46 +++++++
 .../fortran/target-critical-lanes.f90         |  33 +++++
 12 files changed, 411 insertions(+), 119 deletions(-)
 create mode 100644 clang/test/OpenMP/target_critical_lane_serialization.c
 create mode 100644 mlir/test/Target/LLVMIR/openmp-critical-gpu.mlir
 create mode 100644 offload/test/offloading/fortran/target-critical-lanes.f90

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 14382a06db34c..fc9026c575d05 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1679,6 +1679,10 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was 
renamed to `alpha.core.Use
   `default(private)`, which could silently lose writes such as the result of
   a reduction on the nested construct.
 
+- On GPUs, a `critical` region is now run by the threads of each warp one at
+  a time with a loop over the warp's active lanes, instead of a loop over every
+  thread of the team.
+
 ### SYCL Support
 
 - On a `spirv32-unknown-unknown` or `spirv64-unknown-unknown` offload target,
diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index bf8cd97e10166..2d4e8577b88b8 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -1371,73 +1371,39 @@ void 
CGOpenMPRuntimeGPU::emitBarrierCall(CodeGenFunction &CGF,
                       Args);
 }
 
+void CGOpenMPRuntimeGPU::emitLaneSerializedRegion(
+    CodeGenFunction &CGF, llvm::function_ref<void()> BodyGen) {
+  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+  auto BodyGenCB = [&](InsertPointTy, InsertPointTy CodeGenIP,
+                       ArrayRef<llvm::BasicBlock *>) -> llvm::Error {
+    CGF.Builder.restoreIP(CodeGenIP);
+    llvm::BasicBlock *AfterBB =
+        llvm::splitBBWithSuffix(CGF.Builder, /*CreateBranch=*/false, ".after");
+    BodyGen();
+    if (CGF.HaveInsertPoint())
+      CGF.Builder.CreateBr(AfterBB);
+    return llvm::Error::success();
+  };
+  InsertPointTy AfterIP =
+      cantFail(OMPBuilder.createLaneSerializedRegion(CGF.Builder, BodyGenCB));
+  CGF.Builder.restoreIP(AfterIP);
+}
+
 void CGOpenMPRuntimeGPU::emitCriticalRegion(
     CodeGenFunction &CGF, StringRef CriticalName,
     const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
     const Expr *Hint) {
-  llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
-  llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
-  llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
-  llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
-  llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
-
-  auto &RT = static_cast<CGOpenMPRuntimeGPU &>(CGF.CGM.getOpenMPRuntime());
-
-  // Get the mask of active threads in the warp.
-  llvm::Value *Mask = 
CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
-      CGM.getModule(), OMPRTL___kmpc_warp_active_thread_mask));
-  // Fetch team-local id of the thread.
-  llvm::Value *ThreadID = RT.getGPUThreadID(CGF);
-
-  // Get the width of the team.
-  llvm::Value *TeamWidth = RT.getGPUNumThreads(CGF);
-
-  // Initialize the counter variable for the loop.
-  QualType Int32Ty =
-      CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
-  Address Counter = CGF.CreateMemTempWithoutCast(Int32Ty, "critical_counter");
-  LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
-  CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
-                        /*isInit=*/true);
-
-  // Block checks if loop counter exceeds upper bound.
-  CGF.EmitBlock(LoopBB);
-  llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
-  llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
-  CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
-
-  // Block tests which single thread should execute region, and which threads
-  // should go straight to synchronisation point.
-  CGF.EmitBlock(TestBB);
-  CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
-  llvm::Value *CmpThreadToCounter =
-      CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
-  CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
-
-  // Block emits the body of the critical region.
-  CGF.EmitBlock(BodyBB);
-
-  // Output the critical statement.
-  CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
-                                      Hint);
-
-  // After the body surrounded by the critical region, the single executing
-  // thread will jump to the synchronisation point.
-  // Block waits for all threads in current team to finish then increments the
-  // counter variable and returns to the loop.
-  CGF.EmitBlock(SyncBB);
-  // Reconverge active threads in the warp.
-  (void)CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
-                                CGM.getModule(), OMPRTL___kmpc_syncwarp),
-                            Mask);
-
-  llvm::Value *IncCounterVal =
-      CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
-  CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
-  CGF.EmitBranch(LoopBB);
-
-  // Block that is reached when  all threads in the team complete the region.
-  CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
+  if (!CGM.getTarget().getGridValue().GV_Lockstep_Lanes) {
+    CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
+                                        Hint);
+    return;
+  }
+  // Where the threads of a warp run in lockstep, the device runtime lets only
+  // one of them contend for the critical lock, so send each through in turn.
+  emitLaneSerializedRegion(CGF, [&] {
+    CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
+                                        Hint);
+  });
 }
 
 /// Cast value to the specified type.
diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
index 50efbfd1577a5..b30542366ae07 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
@@ -45,6 +45,10 @@ class CGOpenMPRuntimeGPU : public CGOpenMPRuntime {
   };
 
 private:
+  /// Emits code that the active threads of a warp execute one at a time.
+  void emitLaneSerializedRegion(CodeGenFunction &CGF,
+                                llvm::function_ref<void()> BodyGen);
+
   /// Parallel outlined function work for workers to execute.
   llvm::SmallVector<llvm::Function *, 16> Work;
 
diff --git a/clang/test/OpenMP/nvptx_parallel_codegen.cpp 
b/clang/test/OpenMP/nvptx_parallel_codegen.cpp
index f57a010b38015..02d53bfbe7673 100644
--- a/clang/test/OpenMP/nvptx_parallel_codegen.cpp
+++ b/clang/test/OpenMP/nvptx_parallel_codegen.cpp
@@ -288,39 +288,41 @@ int bar(int n){
 // CHECK1-NEXT:    [[DOTGLOBAL_TID__ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:    [[DOTBOUND_TID__ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:    [[A_ADDR:%.*]] = alloca ptr, align 8
-// CHECK1-NEXT:    [[CRITICAL_COUNTER:%.*]] = alloca i32, align 4
 // CHECK1-NEXT:    store ptr [[DOTGLOBAL_TID_]], ptr [[DOTGLOBAL_TID__ADDR]], 
align 8
 // CHECK1-NEXT:    store ptr [[DOTBOUND_TID_]], ptr [[DOTBOUND_TID__ADDR]], 
align 8
 // CHECK1-NEXT:    store ptr [[A]], ptr [[A_ADDR]], align 8
 // CHECK1-NEXT:    [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8, !nonnull 
[[META6]], !align [[META7]]
-// CHECK1-NEXT:    [[TMP1:%.*]] = call i64 @__kmpc_warp_active_thread_mask()
-// CHECK1-NEXT:    [[TMP2:%.*]] = call i32 
@__kmpc_get_hardware_thread_id_in_block()
-// CHECK1-NEXT:    [[NVPTX_NUM_THREADS:%.*]] = call i32 
@__kmpc_get_hardware_num_threads_in_block()
-// CHECK1-NEXT:    store i32 0, ptr [[CRITICAL_COUNTER]], align 4
-// CHECK1-NEXT:    br label [[OMP_CRITICAL_LOOP:%.*]]
-// CHECK1:       omp.critical.loop:
-// CHECK1-NEXT:    [[TMP3:%.*]] = load i32, ptr [[CRITICAL_COUNTER]], align 4
-// CHECK1-NEXT:    [[TMP4:%.*]] = icmp slt i32 [[TMP3]], [[NVPTX_NUM_THREADS]]
-// CHECK1-NEXT:    br i1 [[TMP4]], label [[OMP_CRITICAL_TEST:%.*]], label 
[[OMP_CRITICAL_EXIT:%.*]]
-// CHECK1:       omp.critical.test:
-// CHECK1-NEXT:    [[TMP5:%.*]] = load i32, ptr [[CRITICAL_COUNTER]], align 4
-// CHECK1-NEXT:    [[TMP6:%.*]] = icmp eq i32 [[TMP2]], [[TMP5]]
-// CHECK1-NEXT:    br i1 [[TMP6]], label [[OMP_CRITICAL_BODY:%.*]], label 
[[OMP_CRITICAL_SYNC:%.*]]
-// CHECK1:       omp.critical.body:
-// CHECK1-NEXT:    [[TMP7:%.*]] = load ptr, ptr [[DOTGLOBAL_TID__ADDR]], align 
8
-// CHECK1-NEXT:    [[TMP8:%.*]] = load i32, ptr [[TMP7]], align 4
-// CHECK1-NEXT:    call void @__kmpc_critical(ptr @[[GLOB1]], i32 [[TMP8]], 
ptr @"_gomp_critical_user_$var")
-// CHECK1-NEXT:    [[TMP9:%.*]] = load i32, ptr [[TMP0]], align 4
-// CHECK1-NEXT:    [[INC:%.*]] = add nsw i32 [[TMP9]], 1
+// CHECK1-NEXT:    [[OMP_LANES_MASK:%.*]] = call i64 
@__kmpc_warp_active_thread_mask()
+// CHECK1-NEXT:    [[OMP_LANES_TID:%.*]] = call i32 
@__kmpc_get_hardware_thread_id_in_block()
+// CHECK1-NEXT:    [[OMP_LANES_WARPSIZE:%.*]] = call i32 
@__kmpc_get_warp_size()
+// CHECK1-NEXT:    [[TMP1:%.*]] = sub i32 [[OMP_LANES_WARPSIZE]], 1
+// CHECK1-NEXT:    [[OMP_LANES_LANE:%.*]] = and i32 [[OMP_LANES_TID]], [[TMP1]]
+// CHECK1-NEXT:    [[TMP2:%.*]] = zext i32 [[OMP_LANES_LANE]] to i64
+// CHECK1-NEXT:    [[OMP_LANES_LANEBIT:%.*]] = shl i64 1, [[TMP2]]
+// CHECK1-NEXT:    br label [[OMP_LANES_HEADER:%.*]]
+// CHECK1:       omp.lanes.header:
+// CHECK1-NEXT:    [[OMP_LANES_WAITING:%.*]] = phi i64 [ [[OMP_LANES_MASK]], 
[[ENTRY:%.*]] ], [ [[OMP_LANES_REST:%.*]], [[OMP_LANES_LATCH:%.*]] ]
+// CHECK1-NEXT:    [[TMP3:%.*]] = sub i64 [[OMP_LANES_WAITING]], 1
+// CHECK1-NEXT:    [[OMP_LANES_REST]] = and i64 [[OMP_LANES_WAITING]], [[TMP3]]
+// CHECK1-NEXT:    [[OMP_LANES_NEXT:%.*]] = xor i64 [[OMP_LANES_WAITING]], 
[[OMP_LANES_REST]]
+// CHECK1-NEXT:    [[TMP4:%.*]] = icmp eq i64 [[OMP_LANES_NEXT]], 
[[OMP_LANES_LANEBIT]]
+// CHECK1-NEXT:    br i1 [[TMP4]], label [[OMP_LANES_BODY:%.*]], label 
[[OMP_LANES_LATCH]]
+// CHECK1:       omp.lanes.body:
+// CHECK1-NEXT:    [[TMP5:%.*]] = load ptr, ptr [[DOTGLOBAL_TID__ADDR]], align 
8
+// CHECK1-NEXT:    [[TMP6:%.*]] = load i32, ptr [[TMP5]], align 4
+// CHECK1-NEXT:    call void @__kmpc_critical(ptr @[[GLOB1]], i32 [[TMP6]], 
ptr @"_gomp_critical_user_$var")
+// CHECK1-NEXT:    [[TMP7:%.*]] = load i32, ptr [[TMP0]], align 4
+// CHECK1-NEXT:    [[INC:%.*]] = add nsw i32 [[TMP7]], 1
 // CHECK1-NEXT:    store i32 [[INC]], ptr [[TMP0]], align 4
-// CHECK1-NEXT:    call void @__kmpc_end_critical(ptr @[[GLOB1]], i32 
[[TMP8]], ptr @"_gomp_critical_user_$var")
-// CHECK1-NEXT:    br label [[OMP_CRITICAL_SYNC]]
-// CHECK1:       omp.critical.sync:
-// CHECK1-NEXT:    call void @__kmpc_syncwarp(i64 [[TMP1]])
-// CHECK1-NEXT:    [[TMP10:%.*]] = add nsw i32 [[TMP5]], 1
-// CHECK1-NEXT:    store i32 [[TMP10]], ptr [[CRITICAL_COUNTER]], align 4
-// CHECK1-NEXT:    br label [[OMP_CRITICAL_LOOP]]
-// CHECK1:       omp.critical.exit:
+// CHECK1-NEXT:    call void @__kmpc_end_critical(ptr @[[GLOB1]], i32 
[[TMP6]], ptr @"_gomp_critical_user_$var")
+// CHECK1-NEXT:    br label [[OMP_LANES_BODY_AFTER:%.*]]
+// CHECK1:       omp.lanes.body.after:
+// CHECK1-NEXT:    br label [[OMP_LANES_LATCH]]
+// CHECK1:       omp.lanes.latch:
+// CHECK1-NEXT:    call void @__kmpc_syncwarp(i64 [[OMP_LANES_MASK]])
+// CHECK1-NEXT:    [[TMP8:%.*]] = icmp eq i64 [[OMP_LANES_REST]], 0
+// CHECK1-NEXT:    br i1 [[TMP8]], label [[OMP_LANES_EXIT:%.*]], label 
[[OMP_LANES_HEADER]]
+// CHECK1:       omp.lanes.exit:
 // CHECK1-NEXT:    ret void
 //
 //
@@ -557,39 +559,41 @@ int bar(int n){
 // CHECK2-NEXT:    [[DOTGLOBAL_TID__ADDR:%.*]] = alloca ptr, align 4
 // CHECK2-NEXT:    [[DOTBOUND_TID__ADDR:%.*]] = alloca ptr, align 4
 // CHECK2-NEXT:    [[A_ADDR:%.*]] = alloca ptr, align 4
-// CHECK2-NEXT:    [[CRITICAL_COUNTER:%.*]] = alloca i32, align 4
 // CHECK2-NEXT:    store ptr [[DOTGLOBAL_TID_]], ptr [[DOTGLOBAL_TID__ADDR]], 
align 4
 // CHECK2-NEXT:    store ptr [[DOTBOUND_TID_]], ptr [[DOTBOUND_TID__ADDR]], 
align 4
 // CHECK2-NEXT:    store ptr [[A]], ptr [[A_ADDR]], align 4
 // CHECK2-NEXT:    [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 4, !nonnull 
[[META6]], !align [[META7]]
-// CHECK2-NEXT:    [[TMP1:%.*]] = call i64 @__kmpc_warp_active_thread_mask()
-// CHECK2-NEXT:    [[TMP2:%.*]] = call i32 
@__kmpc_get_hardware_thread_id_in_block()
-// CHECK2-NEXT:    [[NVPTX_NUM_THREADS:%.*]] = call i32 
@__kmpc_get_hardware_num_threads_in_block()
-// CHECK2-NEXT:    store i32 0, ptr [[CRITICAL_COUNTER]], align 4
-// CHECK2-NEXT:    br label [[OMP_CRITICAL_LOOP:%.*]]
-// CHECK2:       omp.critical.loop:
-// CHECK2-NEXT:    [[TMP3:%.*]] = load i32, ptr [[CRITICAL_COUNTER]], align 4
-// CHECK2-NEXT:    [[TMP4:%.*]] = icmp slt i32 [[TMP3]], [[NVPTX_NUM_THREADS]]
-// CHECK2-NEXT:    br i1 [[TMP4]], label [[OMP_CRITICAL_TEST:%.*]], label 
[[OMP_CRITICAL_EXIT:%.*]]
-// CHECK2:       omp.critical.test:
-// CHECK2-NEXT:    [[TMP5:%.*]] = load i32, ptr [[CRITICAL_COUNTER]], align 4
-// CHECK2-NEXT:    [[TMP6:%.*]] = icmp eq i32 [[TMP2]], [[TMP5]]
-// CHECK2-NEXT:    br i1 [[TMP6]], label [[OMP_CRITICAL_BODY:%.*]], label 
[[OMP_CRITICAL_SYNC:%.*]]
-// CHECK2:       omp.critical.body:
-// CHECK2-NEXT:    [[TMP7:%.*]] = load ptr, ptr [[DOTGLOBAL_TID__ADDR]], align 
4
-// CHECK2-NEXT:    [[TMP8:%.*]] = load i32, ptr [[TMP7]], align 4
-// CHECK2-NEXT:    call void @__kmpc_critical(ptr @[[GLOB1]], i32 [[TMP8]], 
ptr @"_gomp_critical_user_$var")
-// CHECK2-NEXT:    [[TMP9:%.*]] = load i32, ptr [[TMP0]], align 4
-// CHECK2-NEXT:    [[INC:%.*]] = add nsw i32 [[TMP9]], 1
+// CHECK2-NEXT:    [[OMP_LANES_MASK:%.*]] = call i64 
@__kmpc_warp_active_thread_mask()
+// CHECK2-NEXT:    [[OMP_LANES_TID:%.*]] = call i32 
@__kmpc_get_hardware_thread_id_in_block()
+// CHECK2-NEXT:    [[OMP_LANES_WARPSIZE:%.*]] = call i32 
@__kmpc_get_warp_size()
+// CHECK2-NEXT:    [[TMP1:%.*]] = sub i32 [[OMP_LANES_WARPSIZE]], 1
+// CHECK2-NEXT:    [[OMP_LANES_LANE:%.*]] = and i32 [[OMP_LANES_TID]], [[TMP1]]
+// CHECK2-NEXT:    [[TMP2:%.*]] = zext i32 [[OMP_LANES_LANE]] to i64
+// CHECK2-NEXT:    [[OMP_LANES_LANEBIT:%.*]] = shl i64 1, [[TMP2]]
+// CHECK2-NEXT:    br label [[OMP_LANES_HEADER:%.*]]
+// CHECK2:       omp.lanes.header:
+// CHECK2-NEXT:    [[OMP_LANES_WAITING:%.*]] = phi i64 [ [[OMP_LANES_MASK]], 
[[ENTRY:%.*]] ], [ [[OMP_LANES_REST:%.*]], [[OMP_LANES_LATCH:%.*]] ]
+// CHECK2-NEXT:    [[TMP3:%.*]] = sub i64 [[OMP_LANES_WAITING]], 1
+// CHECK2-NEXT:    [[OMP_LANES_REST]] = and i64 [[OMP_LANES_WAITING]], [[TMP3]]
+// CHECK2-NEXT:    [[OMP_LANES_NEXT:%.*]] = xor i64 [[OMP_LANES_WAITING]], 
[[OMP_LANES_REST]]
+// CHECK2-NEXT:    [[TMP4:%.*]] = icmp eq i64 [[OMP_LANES_NEXT]], 
[[OMP_LANES_LANEBIT]]
+// CHECK2-NEXT:    br i1 [[TMP4]], label [[OMP_LANES_BODY:%.*]], label 
[[OMP_LANES_LATCH]]
+// CHECK2:       omp.lanes.body:
+// CHECK2-NEXT:    [[TMP5:%.*]] = load ptr, ptr [[DOTGLOBAL_TID__ADDR]], align 
4
+// CHECK2-NEXT:    [[TMP6:%.*]] = load i32, ptr [[TMP5]], align 4
+// CHECK2-NEXT:    call void @__kmpc_critical(ptr @[[GLOB1]], i32 [[TMP6]], 
ptr @"_gomp_critical_user_$var")
+// CHECK2-NEXT:    [[TMP7:%.*]] = load i32, ptr [[TMP0]], align 4
+// CHECK2-NEXT:    [[INC:%.*]] = add nsw i32 [[TMP7]], 1
 // CHECK2-NEXT:    store i32 [[INC]], ptr [[TMP0]], align 4
-// CHECK2-NEXT:    call void @__kmpc_end_critical(ptr @[[GLOB1]], i32 
[[TMP8]], ptr @"_gomp_critical_user_$var")
-// CHECK2-NEXT:    br label [[OMP_CRITICAL_SYNC]]
-// CHECK2:       omp.critical.sync:
-// CHECK2-NEXT:    call void @__kmpc_syncwarp(i64 [[TMP1]])
-// CHECK2-NEXT:    [[TMP10:%.*]] = add nsw i32 [[TMP5]], 1
-// CHECK2-NEXT:    store i32 [[TMP10]], ptr [[CRITICAL_COUNTER]], align 4
-// CHECK2-NEXT:    br label [[OMP_CRITICAL_LOOP]]
-// CHECK2:       omp.critical.exit:
+// CHECK2-NEXT:    call void @__kmpc_end_critical(ptr @[[GLOB1]], i32 
[[TMP6]], ptr @"_gomp_critical_user_$var")
+// CHECK2-NEXT:    br label [[OMP_LANES_BODY_AFTER:%.*]]
+// CHECK2:       omp.lanes.body.after:
+// CHECK2-NEXT:    br label [[OMP_LANES_LATCH]]
+// CHECK2:       omp.lanes.latch:
+// CHECK2-NEXT:    call void @__kmpc_syncwarp(i64 [[OMP_LANES_MASK]])
+// CHECK2-NEXT:    [[TMP8:%.*]] = icmp eq i64 [[OMP_LANES_REST]], 0
+// CHECK2-NEXT:    br i1 [[TMP8]], label [[OMP_LANES_EXIT:%.*]], label 
[[OMP_LANES_HEADER]]
+// CHECK2:       omp.lanes.exit:
 // CHECK2-NEXT:    ret void
 //
 //
diff --git a/clang/test/OpenMP/target_critical_lane_serialization.c 
b/clang/test/OpenMP/target_critical_lane_serialization.c
new file mode 100644
index 0000000000000..ebb8cb9c027cd
--- /dev/null
+++ b/clang/test/OpenMP/target_critical_lane_serialization.c
@@ -0,0 +1,29 @@
+// On a GPU, whose threads of a warp may run in lockstep, a critical region is
+// run by the threads of each warp one at a time, so that only one of them
+// contends for the critical lock.
+
+// RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-unknown 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-host.bc
+// RUN: %clang_cc1 -fopenmp -x c -triple amdgcn-amd-amdhsa 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-target-device 
-fopenmp-host-ir-file-path %t-host.bc -o - | FileCheck %s
+// RUN: %clang_cc1 -fopenmp -x c -triple x86_64-unknown-unknown 
-fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-host-nv.bc
+// RUN: %clang_cc1 -fopenmp -x c -triple nvptx64-nvidia-cuda 
-fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-target-device 
-fopenmp-host-ir-file-path %t-host-nv.bc -o - | FileCheck %s
+// expected-no-diagnostics
+
+#pragma omp declare target
+int X;
+
+// CHECK-LABEL: define {{.*}}void @critical_region(
+// CHECK:       %omp.lanes.mask = call i64 @__kmpc_warp_active_thread_mask()
+// CHECK:       omp.lanes.header:
+// CHECK:       omp.lanes.body:
+// CHECK:         call void @__kmpc_critical(
+// CHECK:         call void @__kmpc_end_critical(
+// CHECK:       omp.lanes.latch:
+// CHECK-NEXT:    call void @__kmpc_syncwarp(i64 %omp.lanes.mask)
+// CHECK:       omp.lanes.exit:
+// CHECK-NOT:   omp.critical.loop
+// CHECK:       ret void
+void critical_region(void) {
+#pragma omp critical
+  X++;
+}
+#pragma omp end declare target
diff --git a/flang/docs/ReleaseNotes.md b/flang/docs/ReleaseNotes.md
index 2550ade41966a..41f006fcba056 100644
--- a/flang/docs/ReleaseNotes.md
+++ b/flang/docs/ReleaseNotes.md
@@ -84,6 +84,9 @@ page](https://llvm.org/releases/).
   the same length.
   ([#220377](https://github.com/llvm/llvm-project/pull/220377))
 
+- Fixed `!$omp critical` on AMDGPU executing its region once per wavefront
+  instead of once per thread: the threads of a wavefront entered the region
+  together on a single acquisition of the lock. Each thread now enters in turn.
 
 ## Non-comprehensive list of changes in this release
 
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPGridValues.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPGridValues.h
index 788a3c8a56f38..47d4231a50d36 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPGridValues.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPGridValues.h
@@ -81,6 +81,14 @@ struct GV {
   constexpr unsigned maxWarpNumber() const {
     return GV_Max_WG_Size / GV_Warp_Size;
   }
+
+  /// Whether the threads of a warp may execute in lockstep, as one instruction
+  /// stream, rather than each making progress independently. A thread then
+  /// cannot wait for another thread of its own warp: while it spins on a lock
+  /// that the other holds, the other cannot run on to release it. Code in 
which
+  /// one thread may wait for another, such as a critical region, has to be run
+  /// by the threads of each warp one at a time. This is assumed of every GPU.
+  bool GV_Lockstep_Lanes;
 };
 
 /// For AMDGPU GPUs
@@ -92,6 +100,7 @@ static constexpr GV AMDGPUGridValues64 = {
     896,       // GV_SimpleBufferSize
     1024,      // GV_Max_WG_Size,
     256,       // GV_Default_WG_Size
+    true,      // GV_Lockstep_Lanes
 };
 
 static constexpr GV AMDGPUGridValues32 = {
@@ -102,6 +111,7 @@ static constexpr GV AMDGPUGridValues32 = {
     896,       // GV_SimpleBufferSize
     1024,      // GV_Max_WG_Size,
     256,       // GV_Default_WG_Size
+    true,      // GV_Lockstep_Lanes
 };
 
 template <unsigned wavesize> constexpr const GV &getAMDGPUGridValues() {
@@ -118,6 +128,7 @@ static constexpr GV NVPTXGridValues = {
     896,       // GV_SimpleBufferSize
     1024,      // GV_Max_WG_Size
     128,       // GV_Default_WG_Size
+    true,      // GV_Lockstep_Lanes
 };
 
 /// For generic SPIR-V GPUs
@@ -129,6 +140,7 @@ static constexpr GV SPIRVGridValues = {
     896,       // GV_SimpleBufferSize
     1024,      // GV_Max_WG_Size,
     256,       // GV_Default_WG_Size
+    true,      // GV_Lockstep_Lanes
 };
 
 } // namespace omp
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index 063610355e3a1..9c4decf10f2b2 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -3357,8 +3357,33 @@ class OpenMPIRBuilder {
                                            bool IsInclusive,
                                            ScanInfo *ScanRedInfo);
 
+  /// Generator for a region that the active lanes of a GPU warp or wavefront
+  /// execute one at a time, in lane order.
+  ///
+  /// The lanes of a warp share an instruction stream, so a lane that takes a
+  /// lock inside a region cannot release it while other lanes of its warp are
+  /// still spinning for that lock. Running the lanes through the region one by
+  /// one lets each of them take and release the lock in turn. The region is
+  /// emitted as a loop over the warp's active-lane mask that runs the body 
only
+  /// in the lowest lane not yet served, synchronizing the warp after each 
step.
+  ///
+  /// \param Loc The insert and source location description.
+  /// \param BodyGenCB Callback that will generate the region body code. It is
+  ///                  called with an insertion point in a block whose
+  ///                  terminator continues the loop; the code it generates
+  ///                  must reach that terminator.
+  ///
+  /// \returns The insertion position *after* the region.
+  LLVM_ABI InsertPointOrErrorTy createLaneSerializedRegion(
+      const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB);
+
   /// Generator for '#omp critical'
   ///
+  /// Where the threads of a warp run in lockstep (omp::GV::GV_Lockstep_Lanes),
+  /// the region is serialized over the lanes of each warp (see
+  /// createLaneSerializedRegion) before the lock is taken, so that lanes of 
the
+  /// same warp do not contend for it.
+  ///
   /// \param Loc The insert and source location description.
   /// \param BodyGenCB Callback that will generate the region body code.
   /// \param FiniCB Callback to finalize variable copies.
@@ -4028,6 +4053,14 @@ class OpenMPIRBuilder {
                                                Instruction *ExitCall,
                                                bool HasFinalize = true);
 
+  /// Emit the lock calls and body of a critical region, without the lane
+  /// serialization that createCritical adds on a GPU.
+  InsertPointOrErrorTy emitCriticalRegion(const LocationDescription &Loc,
+                                          BodyGenCallbackTy BodyGenCB,
+                                          FinalizeCallbackTy FiniCB,
+                                          StringRef CriticalName,
+                                          Value *HintInst);
+
   /// Common Interface to generate OMP inlined regions
   ///
   /// \param OMPD Directive to generate inlined region for
diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 292ff872fbeea..8544d11bae336 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -8165,6 +8165,69 @@ OpenMPIRBuilder::createScope(const LocationDescription 
&Loc,
   return Builder.saveIP();
 }
 
+OpenMPIRBuilder::InsertPointOrErrorTy
+OpenMPIRBuilder::createLaneSerializedRegion(const LocationDescription &Loc,
+                                            BodyGenCallbackTy BodyGenCB) {
+  if (!updateToLocation(Loc))
+    return Loc.IP;
+
+  // Everything after the insertion point continues once every lane is done.
+  BasicBlock *ExitBB =
+      splitBB(Builder, /*CreateBranch=*/false, "omp.lanes.exit");
+  BasicBlock *EntryBB = Builder.GetInsertBlock();
+  Function *F = EntryBB->getParent();
+  LLVMContext &Ctx = M.getContext();
+
+  Value *Mask = createRuntimeFunctionCall(
+      getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_warp_active_thread_mask), {},
+      "omp.lanes.mask");
+  Value *ThreadId = createRuntimeFunctionCall(
+      getOrCreateRuntimeFunctionPtr(
+          OMPRTL___kmpc_get_hardware_thread_id_in_block),
+      {}, "omp.lanes.tid");
+  Value *WarpSize = createRuntimeFunctionCall(
+      getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_get_warp_size), {},
+      "omp.lanes.warpsize");
+  // The warp size is a power of two.
+  Value *Lane = Builder.CreateAnd(
+      ThreadId, Builder.CreateSub(WarpSize, Builder.getInt32(1)),
+      "omp.lanes.lane");
+  Value *LaneBit =
+      Builder.CreateShl(Builder.getInt64(1), Builder.CreateZExt(Lane, Int64),
+                        "omp.lanes.lanebit");
+
+  BasicBlock *HeaderBB = BasicBlock::Create(Ctx, "omp.lanes.header", F, 
ExitBB);
+  BasicBlock *BodyBB = BasicBlock::Create(Ctx, "omp.lanes.body", F, ExitBB);
+  BasicBlock *LatchBB = BasicBlock::Create(Ctx, "omp.lanes.latch", F, ExitBB);
+  Builder.CreateBr(HeaderBB);
+
+  // Each iteration serves the lowest lane that is still waiting.
+  Builder.SetInsertPoint(HeaderBB);
+  PHINode *Waiting = Builder.CreatePHI(Int64, 2, "omp.lanes.waiting");
+  Waiting->addIncoming(Mask, EntryBB);
+  Value *Rest = Builder.CreateAnd(
+      Waiting, Builder.CreateSub(Waiting, Builder.getInt64(1)),
+      "omp.lanes.rest");
+  Value *Next = Builder.CreateXor(Waiting, Rest, "omp.lanes.next");
+  Builder.CreateCondBr(Builder.CreateICmpEQ(Next, LaneBit), BodyBB, LatchBB);
+
+  Builder.SetInsertPoint(BodyBB);
+  Instruction *BodyTerm = Builder.CreateBr(LatchBB);
+
+  Builder.SetInsertPoint(LatchBB);
+  createRuntimeFunctionCall(
+      getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_syncwarp), {Mask});
+  Waiting->addIncoming(Rest, LatchBB);
+  Builder.CreateCondBr(Builder.CreateIsNull(Rest), ExitBB, HeaderBB);
+
+  if (Error Err = BodyGenCB(/*AllocaIP=*/InsertPointTy(),
+                            BodyTerm->getIterator(), /*DeallocBlocks=*/{}))
+    return Err;
+
+  Builder.SetInsertPoint(ExitBB->getFirstInsertionPt());
+  return Builder.saveIP();
+}
+
 OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::createCritical(
     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
@@ -8172,6 +8235,31 @@ OpenMPIRBuilder::InsertPointOrErrorTy 
OpenMPIRBuilder::createCritical(
   if (!updateToLocation(Loc))
     return Loc.IP;
 
+  // Where the threads of a warp run in lockstep they cannot wait for one
+  // another (see createLaneSerializedRegion), so the device runtime lets only
+  // one of them contend for the critical lock. Send each through in turn.
+  const Triple &T = M.getTargetTriple();
+  if (Config.IsGPU.value_or(false) && hasGridValue(T) &&
+      getGridValue(T, Builder.GetInsertBlock()->getParent())
+          .GV_Lockstep_Lanes) {
+    auto CriticalCB = [&](InsertPointTy, InsertPointTy CodeGenIP,
+                          ArrayRef<BasicBlock *>) -> Error {
+      InsertPointOrErrorTy AfterIP =
+          emitCriticalRegion(LocationDescription(CodeGenIP, Loc.DL), BodyGenCB,
+                             FiniCB, CriticalName, HintInst);
+      return AfterIP.takeError();
+    };
+    return createLaneSerializedRegion(Loc, CriticalCB);
+  }
+  return emitCriticalRegion(Loc, BodyGenCB, FiniCB, CriticalName, HintInst);
+}
+
+OpenMPIRBuilder::InsertPointOrErrorTy OpenMPIRBuilder::emitCriticalRegion(
+    const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
+    FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
+  if (!updateToLocation(Loc))
+    return Loc.IP;
+
   Directive OMPD = Directive::OMPD_critical;
   uint32_t SrcLocStrSize;
   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc, SrcLocStrSize);
diff --git a/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp 
b/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
index 45a244a1d1ab3..7d5d98914e11a 100644
--- a/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ b/llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -6,6 +6,7 @@
 //
 
//===----------------------------------------------------------------------===//
 
+#include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Frontend/OpenMP/OMPConstants.h"
 #include "llvm/Frontend/OpenMP/OMPDeviceConstants.h"
 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
@@ -15,6 +16,7 @@
 #include "llvm/IR/DIBuilder.h"
 #include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DebugProgramInstruction.h"
+#include "llvm/IR/Dominators.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/InstIterator.h"
 #include "llvm/IR/Instructions.h"
@@ -3147,6 +3149,74 @@ TEST_F(OpenMPIRBuilderTest, CriticalDirective) {
     EXPECT_EQ(*Alignment, std::max(TypeAlign, PtrAlign));
 }
 
+TEST_F(OpenMPIRBuilderTest, CriticalDirectiveAMDGPU) {
+  using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
+  M->setTargetTriple(Triple("amdgcn-amd-amdhsa"));
+  OpenMPIRBuilder OMPBuilder(*M);
+  OMPBuilder.setConfig(OpenMPIRBuilderConfig(
+      /*IsTargetDevice=*/true, /*IsGPU=*/true,
+      /*OpenMPOffloadMandatory=*/false, /*HasRequiresReverseOffload=*/false,
+      /*HasRequiresUnifiedAddress=*/false,
+      /*HasRequiresUnifiedSharedMemory=*/false,
+      /*HasRequiresDynamicAllocators=*/false));
+  OMPBuilder.initialize();
+  F->setName("func");
+  IRBuilder<> Builder(BB);
+
+  Type *PrivType = F->arg_begin()->getType();
+  AllocaInst *PrivAI = Builder.CreateAlloca(PrivType, /*AddrSpace=*/5);
+  StoreInst *BodyStore = nullptr;
+
+  auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
+                       ArrayRef<BasicBlock *> DeallocBlocks) {
+    Builder.restoreIP(CodeGenIP);
+    BodyStore = Builder.CreateStore(F->arg_begin(), PrivAI);
+  };
+  auto FiniCB = [&](InsertPointTy IP) {};
+
+  ASSERT_EXPECTED_INIT(
+      OpenMPIRBuilder::InsertPointTy, AfterIP,
+      OMPBuilder.createCritical(Builder, BODYGENCB_WRAPPER(BodyGenCB),
+                                FINICB_WRAPPER(FiniCB), "testCRT", nullptr));
+  Builder.restoreIP(AfterIP);
+  Builder.CreateRetVoid();
+  OMPBuilder.finalize();
+  EXPECT_FALSE(verifyModule(*M, &errs()));
+
+  auto FindCall = [&](StringRef Name) -> CallInst * {
+    for (Instruction &I : instructions(*F))
+      if (auto *CI = dyn_cast<CallInst>(&I))
+        if (CI->getCalledFunction() &&
+            CI->getCalledFunction()->getName() == Name)
+          return CI;
+    return nullptr;
+  };
+  CallInst *MaskCI = FindCall("__kmpc_warp_active_thread_mask");
+  CallInst *EnterCI = FindCall("__kmpc_critical");
+  CallInst *ExitCI = FindCall("__kmpc_end_critical");
+  CallInst *SyncCI = FindCall("__kmpc_syncwarp");
+  ASSERT_NE(MaskCI, nullptr);
+  ASSERT_NE(EnterCI, nullptr);
+  ASSERT_NE(ExitCI, nullptr);
+  ASSERT_NE(SyncCI, nullptr);
+  ASSERT_NE(BodyStore, nullptr);
+  EXPECT_EQ(SyncCI->getArgOperand(0), MaskCI);
+
+  // The lock is taken and released inside a loop over the active lanes, which
+  // the warp synchronizes on at the end of each iteration.
+  DominatorTree DT(*F);
+  LoopInfo LI(DT);
+  Loop *L = LI.getLoopFor(SyncCI->getParent());
+  ASSERT_NE(L, nullptr);
+  EXPECT_TRUE(L->contains(EnterCI));
+  EXPECT_TRUE(L->contains(BodyStore));
+  EXPECT_TRUE(L->contains(ExitCI));
+  EXPECT_FALSE(L->contains(MaskCI));
+  EXPECT_TRUE(isa<PHINode>(L->getHeader()->front()));
+  EXPECT_TRUE(DT.dominates(EnterCI, BodyStore));
+  EXPECT_TRUE(DT.dominates(BodyStore, ExitCI));
+}
+
 TEST_F(OpenMPIRBuilderTest, OrderedDirectiveDependSource) {
   using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
   OpenMPIRBuilder OMPBuilder(*M);
diff --git a/mlir/test/Target/LLVMIR/openmp-critical-gpu.mlir 
b/mlir/test/Target/LLVMIR/openmp-critical-gpu.mlir
new file mode 100644
index 0000000000000..3649423477c58
--- /dev/null
+++ b/mlir/test/Target/LLVMIR/openmp-critical-gpu.mlir
@@ -0,0 +1,46 @@
+// RUN: mlir-translate -mlir-to-llvmir -split-input-file %s | FileCheck %s
+
+// On a GPU, whose threads of a warp may run in lockstep, the threads of each
+// warp enter a critical region one at a time, so that threads sharing an
+// instruction stream never spin for a lock that one of them holds.
+
+module attributes {llvm.target_triple = "amdgcn-amd-amdhsa", 
omp.is_target_device = true, omp.is_gpu = true} {
+  // CHECK-LABEL: define {{.*}}void @omp_critical_amdgpu(
+  // CHECK:       %omp.lanes.mask = call i64 @__kmpc_warp_active_thread_mask()
+  // CHECK:       omp.lanes.header:
+  // CHECK:         %omp.lanes.waiting = phi i64 [ %omp.lanes.mask, %{{.*}} ], 
[ %omp.lanes.rest, %omp.lanes.latch ]
+  // CHECK:       omp.lanes.body:
+  // CHECK:         call void @__kmpc_critical(
+  // CHECK:         store i32 %{{.*}}, ptr %{{.*}}
+  // CHECK:         call void @__kmpc_end_critical(
+  // CHECK:       omp.lanes.latch:
+  // CHECK-NEXT:    call void @__kmpc_syncwarp(i64 %omp.lanes.mask)
+  // CHECK:       omp.lanes.exit:
+  // CHECK-NEXT:    ret void
+  llvm.func @omp_critical_amdgpu(%x : !llvm.ptr, %xval : i32) attributes 
{omp.declare_target = #omp.declaretarget<device_type = nohost, capture_clause = 
to>} {
+    omp.critical {
+      llvm.store %xval, %x : i32, !llvm.ptr
+      omp.terminator
+    }
+    llvm.return
+  }
+}
+
+// -----
+
+module attributes {llvm.target_triple = "nvptx64-nvidia-cuda", 
omp.is_target_device = true, omp.is_gpu = true} {
+  // CHECK-LABEL: define {{.*}}void @omp_critical_nvptx(
+  // CHECK:       %omp.lanes.mask = call i64 @__kmpc_warp_active_thread_mask()
+  // CHECK:       omp.lanes.body:
+  // CHECK:         call void @__kmpc_critical(
+  // CHECK:         call void @__kmpc_end_critical(
+  // CHECK:       omp.lanes.latch:
+  // CHECK-NEXT:    call void @__kmpc_syncwarp(i64 %omp.lanes.mask)
+  llvm.func @omp_critical_nvptx(%x : !llvm.ptr, %xval : i32) attributes 
{omp.declare_target = #omp.declaretarget<device_type = nohost, capture_clause = 
to>} {
+    omp.critical {
+      llvm.store %xval, %x : i32, !llvm.ptr
+      omp.terminator
+    }
+    llvm.return
+  }
+}
diff --git a/offload/test/offloading/fortran/target-critical-lanes.f90 
b/offload/test/offloading/fortran/target-critical-lanes.f90
new file mode 100644
index 0000000000000..293ff62246763
--- /dev/null
+++ b/offload/test/offloading/fortran/target-critical-lanes.f90
@@ -0,0 +1,33 @@
+! Every thread of a team takes the critical lock once, including threads that
+! share a wavefront. A critical construct only excludes threads of the same
+! contention group, so each team counts its own threads.
+! REQUIRES: flang, amdgpu
+
+! RUN: %libomptarget-compile-fortran-run-and-check-generic
+program main
+  use omp_lib
+  implicit none
+  integer, parameter :: nteams = 4
+  integer :: counts(nteams), expected(nteams), t
+
+  counts = 0
+  expected = 0
+  !$omp target teams num_teams(nteams) map(tofrom: counts, expected)
+  !$omp parallel num_threads(256) private(t)
+  t = omp_get_team_num() + 1
+  !$omp critical
+  counts(t) = counts(t) + 1
+  !$omp end critical
+  !$omp atomic
+  expected(t) = expected(t) + 1
+  !$omp end parallel
+  !$omp end target teams
+
+  if (all(counts == expected) .and. sum(counts) > 0) then
+    print *, "PASS"
+  else
+    print *, "FAIL", counts, expected
+  end if
+end program main
+
+! CHECK: PASS

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to