See attached patch, 4/10 of v2 of the DO CONCURRENT to OpenMP series.

Changes since v1: dc_device_var_ok also rejects assumed-type variables,
and dc_build_clauses maps the outer variable of a LOCAL_INIT spec 'to':
mapped tofrom implicitly, it faulted for a constant actual argument.

Start at gfc_trans_omp_do_concurrent in trans-openmp.cc, which now
wraps the loop nest in a target construct for =device and skips it when
dc_has_iterations finds no iterations.  dc_has_iterations exists
because plain lastprivate, which DISTRIBUTE requires, leaves the
variable unspecified after zero iterations.

dc_device_ok, called from gfc_dc_omp_lowering, lists when a construct
runs on the host instead.  dc_device_var_ok, called from dc_scan_expr
and dc_device_ok, rejects variables that cannot be mapped.

The PURE/ELEMENTAL/declare-target rule in dc_device_ok, which 8/10
replaces, is there because on amdgcn a target region nested in device
code returns without running its body (libgomp/config/gcn/target.c).

dc_build_clauses, with dc_mapped_implicitly, maps 'to' what the body
does not define, because copying a constant actual argument back
faults on the GPU: its storage is read-only.  The dc_scan and
dc_scan_def hunks record what the body defines for it.  The
flag-types.h, lang.opt, trans-stmt.cc and trans.h hunks are mechanical.

Regards,

Jerry

---

fortran: [PR128590]-4 Add -fdo-concurrent-to-openmp=device

Translate DO CONCURRENT into 'target teams distribute parallel do simd'
through gfc_trans_omp_target.  Scalars that the body defines in place,
which a target construct otherwise makes firstprivate, are mapped tofrom.
What the body does not define, and the outer variable of a LOCAL_INIT
spec, is mapped 'to' only, because copying it back could write to
read-only storage, such as that of a constant actual argument.

DISTRIBUTE does not allow conditional lastprivate, so privatized
variables get plain lastprivate, which is right only if every iteration
defines them, and the construct is skipped when it has no iterations.  A
definition in an IF or loop construct, or after a CYCLE, a GOTO or an
EXIT from a BLOCK construct, is not made by every iteration.

A construct runs on the host instead if it is in a PURE, ELEMENTAL or
declare target procedure, which may itself run on the device, where a
nested target region does not run its body; if it calls a procedure; if
it references a variable that cannot be mapped implicitly, such as an
assumed-size or assumed-type array or a pointer; or if only some
iterations may define a privatized variable.

Assisted-by: Claude Opus 5.5

        PR fortran/128590

gcc/ChangeLog:

        * flag-types.h (enum gfc_dc_to_omp): Add GFC_DC_OMP_DEVICE.

gcc/fortran/ChangeLog:

        * invoke.texi: Document -fdo-concurrent-to-openmp=device.
        * lang.opt (fdo-concurrent-to-openmp=): Add device.
        * trans-openmp.cc (struct dc_scan): Record defined variables, defined
        scalar parts and variables that cannot be mapped.
        (dc_scan_def): Record defined variables and scalar parts.
        (dc_device_var_ok, dc_device_ok, dc_has_iterations)
        (dc_mapped_implicitly): New.
        (dc_scan_expr): Record variables that cannot be mapped.
        (dc_scan_body): Reset them for each walk.
        (gfc_dc_omp_lowering): Return GFC_DC_OMP_DEVICE for constructs that
        can be offloaded.
        (dc_build_clauses): Add a DEVICE parameter; map scalars defined in
        place tofrom, and what the body does not define and LOCAL_INIT
        variables to, and use plain lastprivate.
        (gfc_trans_omp_do_concurrent): Add a KIND parameter.  Translate an
        offloaded construct with gfc_trans_omp_target, skipping it if it
        has no iterations.
        * trans-stmt.cc (gfc_trans_do_concurrent): Pass the lowering kind.
        * trans.h (gfc_trans_omp_do_concurrent): Update.

gcc/testsuite/ChangeLog:

        * gfortran.dg/gomp/do_concurrent_to_openmp_6.f90: New test.
        * gfortran.dg/gomp/do_concurrent_to_openmp_7.f90: New test.
        * gfortran.dg/gomp/do_concurrent_to_openmp_16.f90: New test.

libgomp/ChangeLog:

        * testsuite/libgomp.fortran/do_concurrent_to_openmp_4.f90: New test.
        * testsuite/libgomp.fortran/do_concurrent_to_openmp_5.f90: New test.
>From c8f01e43e45e56dab8f1b943fb2f6732d6f7c0a6 Mon Sep 17 00:00:00 2001
From: Jerry DeLisle <[email protected]>
Date: Wed, 25 Nov 2026 15:50:22 -0800
Subject: [PATCH v2 4/10] fortran: [PR128590]-4 Add
 -fdo-concurrent-to-openmp=device

Translate DO CONCURRENT into 'target teams distribute parallel do simd'
through gfc_trans_omp_target.  Scalars that the body defines in place,
which a target construct otherwise makes firstprivate, are mapped tofrom.
What the body does not define, and the outer variable of a LOCAL_INIT
spec, is mapped 'to' only, because copying it back could write to
read-only storage, such as that of a constant actual argument.

DISTRIBUTE does not allow conditional lastprivate, so privatized
variables get plain lastprivate, which is right only if every iteration
defines them, and the construct is skipped when it has no iterations.  A
definition in an IF or loop construct, or after a CYCLE, a GOTO or an
EXIT from a BLOCK construct, is not made by every iteration.

A construct runs on the host instead if it is in a PURE, ELEMENTAL or
declare target procedure, which may itself run on the device, where a
nested target region does not run its body; if it calls a procedure; if
it references a variable that cannot be mapped implicitly, such as an
assumed-size or assumed-type array or a pointer; or if only some
iterations may define a privatized variable.

Assisted-by: Claude Opus 5.5

	PR fortran/128590

gcc/ChangeLog:

	* flag-types.h (enum gfc_dc_to_omp): Add GFC_DC_OMP_DEVICE.

gcc/fortran/ChangeLog:

	* invoke.texi: Document -fdo-concurrent-to-openmp=device.
	* lang.opt (fdo-concurrent-to-openmp=): Add device.
	* trans-openmp.cc (struct dc_scan): Record defined variables, defined
	scalar parts and variables that cannot be mapped.
	(dc_scan_def): Record defined variables and scalar parts.
	(dc_device_var_ok, dc_device_ok, dc_has_iterations)
	(dc_mapped_implicitly): New.
	(dc_scan_expr): Record variables that cannot be mapped.
	(dc_scan_body): Reset them for each walk.
	(gfc_dc_omp_lowering): Return GFC_DC_OMP_DEVICE for constructs that
	can be offloaded.
	(dc_build_clauses): Add a DEVICE parameter; map scalars defined in
	place tofrom, and what the body does not define and LOCAL_INIT
	variables to, and use plain lastprivate.
	(gfc_trans_omp_do_concurrent): Add a KIND parameter.  Translate an
	offloaded construct with gfc_trans_omp_target, skipping it if it
	has no iterations.
	* trans-stmt.cc (gfc_trans_do_concurrent): Pass the lowering kind.
	* trans.h (gfc_trans_omp_do_concurrent): Update.

gcc/testsuite/ChangeLog:

	* gfortran.dg/gomp/do_concurrent_to_openmp_6.f90: New test.
	* gfortran.dg/gomp/do_concurrent_to_openmp_7.f90: New test.
	* gfortran.dg/gomp/do_concurrent_to_openmp_16.f90: New test.

libgomp/ChangeLog:

	* testsuite/libgomp.fortran/do_concurrent_to_openmp_4.f90: New test.
	* testsuite/libgomp.fortran/do_concurrent_to_openmp_5.f90: New test.
---
 gcc/flag-types.h                              |   3 +-
 gcc/fortran/invoke.texi                       |  21 +-
 gcc/fortran/lang.opt                          |   5 +-
 gcc/fortran/trans-openmp.cc                   | 231 ++++++++++++++++--
 gcc/fortran/trans-stmt.cc                     |   5 +-
 gcc/fortran/trans.h                           |   2 +-
 .../gomp/do_concurrent_to_openmp_16.f90       |  38 +++
 .../gomp/do_concurrent_to_openmp_6.f90        | 100 ++++++++
 .../gomp/do_concurrent_to_openmp_7.f90        |  90 +++++++
 .../do_concurrent_to_openmp_4.f90             | 138 +++++++++++
 .../do_concurrent_to_openmp_5.f90             |  77 ++++++
 11 files changed, 689 insertions(+), 21 deletions(-)
 create mode 100644 gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_16.f90
 create mode 100644 gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_6.f90
 create mode 100644 gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_7.f90
 create mode 100644 libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_4.f90
 create mode 100644 libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_5.f90

diff --git a/gcc/flag-types.h b/gcc/flag-types.h
index 6c2ba66d6df..b81e6486f51 100644
--- a/gcc/flag-types.h
+++ b/gcc/flag-types.h
@@ -466,7 +466,8 @@ enum gfc_fcoarray
 enum gfc_dc_to_omp
 {
   GFC_DC_OMP_NONE = 0,
-  GFC_DC_OMP_HOST
+  GFC_DC_OMP_HOST,
+  GFC_DC_OMP_DEVICE
 };
 
 
diff --git a/gcc/fortran/invoke.texi b/gcc/fortran/invoke.texi
index a228275cb66..986a7f88485 100644
--- a/gcc/fortran/invoke.texi
+++ b/gcc/fortran/invoke.texi
@@ -193,7 +193,7 @@ and warnings}.
 -fcheck-array-temporaries
 -fcheck=<all|array-temps|bits|bounds|do|mem|pointer|recursion>
 -fcoarray=<none|single|shared|lib>
--fdo-concurrent-to-openmp=<none|host>
+-fdo-concurrent-to-openmp=<none|host|device>
 -fexternal-blas -fexternal-blas64 -ff2c
 -ffrontend-loop-interchange -ffrontend-optimize
 -finit-character=@var{n} -finit-integer=@var{n} -finit-local-zero
@@ -1889,6 +1889,25 @@ thread, and afterwards has the value from the iteration that defined it
 last.  A construct whose body references such a variable before
 defining it, as an accumulation without a @code{REDUCE} locality spec
 does, is translated serially.
+
+@item @samp{device}
+Translate @code{DO CONCURRENT} constructs into OpenMP @code{target teams
+distribute parallel do simd} loops that run on the default device, or on
+the host when no device is available, see @option{-foffload}.  Variables
+are mapped implicitly as OpenMP prescribes, apart from scalars that the
+body defines in place, such as @code{SHARED} variables, which are mapped
+@code{tofrom}, and variables that the body does not define, which are
+mapped @code{to} rather than @code{tofrom}.  Enclosing constructs in an
+@code{!$omp target data} region keeps their arrays on the device between
+them.  A construct that cannot be offloaded is translated as with
+@samp{host}; this applies to a construct in a @code{PURE},
+@code{ELEMENTAL} or @code{declare target} procedure, which may itself run
+on the device, to one that references a procedure, an assumed-size
+array, a pointer, a polymorphic variable, or a variable of derived type
+with allocatable or pointer components, and to one in which only some
+iterations define a variable of unspecified locality.  A procedure
+containing a construct translated this way must not be called in a
+@code{target} region.
 @end table
 
 The standard permits the iterations of a @code{DO CONCURRENT} construct
diff --git a/gcc/fortran/lang.opt b/gcc/fortran/lang.opt
index a5082eb5679..2d7ae70b971 100644
--- a/gcc/fortran/lang.opt
+++ b/gcc/fortran/lang.opt
@@ -560,7 +560,7 @@ Set the default real kind to an 16 byte wide type.
 
 fdo-concurrent-to-openmp=
 Fortran RejectNegative Joined Enum(gfc_dc_to_omp) Var(flag_do_concurrent_to_openmp) Init(GFC_DC_OMP_NONE)
--fdo-concurrent-to-openmp=<none|host>	Lower DO CONCURRENT constructs to OpenMP loops.
+-fdo-concurrent-to-openmp=<none|host|device>	Lower DO CONCURRENT constructs to OpenMP loops.
 
 Enum
 Name(gfc_dc_to_omp) Type(enum gfc_dc_to_omp) UnknownError(Unrecognized option: %qs)
@@ -571,6 +571,9 @@ Enum(gfc_dc_to_omp) String(none) Value(GFC_DC_OMP_NONE)
 EnumValue
 Enum(gfc_dc_to_omp) String(host) Value(GFC_DC_OMP_HOST)
 
+EnumValue
+Enum(gfc_dc_to_omp) String(device) Value(GFC_DC_OMP_DEVICE)
+
 fdollar-ok
 Fortran Var(flag_dollar_ok)
 Allow dollar signs in entity names.
diff --git a/gcc/fortran/trans-openmp.cc b/gcc/fortran/trans-openmp.cc
index 620882264d6..2c5ed8aa6c3 100644
--- a/gcc/fortran/trans-openmp.cc
+++ b/gcc/fortran/trans-openmp.cc
@@ -11034,6 +11034,8 @@ struct dc_scan
   hash_set<gfc_namespace *> inner;
   /* Designators that the body defines without referencing them.  */
   hash_set<gfc_expr *> defs;
+  /* Variables of which the body defines a part or the whole.  */
+  hash_set<gfc_symbol *> defined;
   /* Uses of variables of unspecified locality, and the variables in the
      order of their first use.  */
   hash_map<gfc_symbol *, dc_use> uses;
@@ -11056,6 +11058,11 @@ struct dc_scan
   /* The body defines a part of a variable that does not depend on
      INDEX_SYMS.  */
   bool unindexed_def;
+  /* Scalars of which the body defines parts.  */
+  hash_set<gfc_symbol *> part_def_seen;
+  auto_vec<gfc_symbol *> part_defs;
+  /* The body references a variable that offloading does not support.  */
+  bool device_bad;
   /* The body references a procedure other than an intrinsic one, and one
      that can see the variables of the procedure containing DC.  */
   bool calls, internal_calls;
@@ -11245,6 +11252,7 @@ dc_scan_def (dc_scan *scan, gfc_expr *e, enum dc_def_kind kind)
       return;
     }
 
+  scan->defined.add (sym);
   if (kind != DC_DEF_REF)
     scan->defs.add (e);
 
@@ -11273,6 +11281,9 @@ dc_scan_def (dc_scan *scan, gfc_expr *e, enum dc_def_kind kind)
 	 iteration; any other part may be shared between iterations.  */
       if (!dc_indexed_designator (scan, e, spec))
 	scan->unindexed_def = true;
+      else if (e->rank == 0 && !sym->attr.dimension
+	       && !scan->part_def_seen.add (sym))
+	scan->part_defs.safe_push (sym);
       return;
     }
 
@@ -11459,6 +11470,33 @@ dc_scan_code (gfc_code **cp, int *, void *data)
 }
 
 
+/* True if the implicit or explicit mapping of SYM to a device is known to
+   work.  An assumed-size array cannot be mapped implicitly, and the
+   others would need a deep or pointer-attaching map.  */
+
+static bool
+dc_device_var_ok (gfc_symbol *sym)
+{
+  if ((sym->as && sym->as->type == AS_ASSUMED_SIZE)
+      || sym->attr.pointer || sym->attr.proc_pointer
+      || sym->attr.cray_pointer || sym->attr.cray_pointee
+      || sym->attr.codimension || sym->attr.threadprivate
+      || sym->attr.in_common
+      || sym->ts.type == BT_CLASS || sym->ts.type == BT_ASSUMED
+      || (sym->ts.type == BT_CHARACTER && sym->ts.deferred))
+    return false;
+
+  if (sym->ts.type == BT_DERIVED
+      && (sym->ts.u.derived->attr.alloc_comp
+	  || sym->ts.u.derived->attr.pointer_comp
+	  || sym->ts.u.derived->attr.proc_pointer_comp
+	  || sym->ts.u.derived->attr.pdt_type))
+    return false;
+
+  return true;
+}
+
+
 static int
 dc_scan_expr (gfc_expr **ep, int *, void *data)
 {
@@ -11483,10 +11521,14 @@ dc_scan_expr (gfc_expr **ep, int *, void *data)
 	gfc_symbol *sym = e->symtree->n.sym;
 	/* A procedure actual argument may be called.  */
 	if (sym->attr.flavor == FL_PROCEDURE && !dc_result_var (sym))
-	  dc_scan_call (scan, sym);
-	else if ((sym->attr.flavor == FL_VARIABLE || dc_result_var (sym))
-		 && !scan->defs.contains (e)
-		 && !dc_locality_known (scan, sym))
+	  {
+	    dc_scan_call (scan, sym);
+	    break;
+	  }
+	bool var = sym->attr.flavor == FL_VARIABLE || dc_result_var (sym);
+	if (var && !dc_device_var_ok (sym))
+	  scan->device_bad = true;
+	if (var && !scan->defs.contains (e) && !dc_locality_known (scan, sym))
 	  {
 	    dc_use &use = dc_use_of (scan, sym);
 	    if (!scan->dom.contains (sym))
@@ -11652,6 +11694,7 @@ dc_scan_body (gfc_code *code, dc_scan *scan)
       scan->nonindex_defs.empty ();
       scan->inner.empty ();
       scan->defs.empty ();
+      scan->defined.empty ();
       scan->uses.empty ();
       scan->order.truncate (0);
       scan->dom.empty ();
@@ -11659,7 +11702,9 @@ dc_scan_body (gfc_code *code, dc_scan *scan)
       scan->cond_depth = 0;
       scan->branched = scan->calls = scan->internal_calls = false;
       scan->exits = 0;
-      scan->unindexed_def = false;
+      scan->unindexed_def = scan->device_bad = false;
+      scan->part_def_seen.empty ();
+      scan->part_defs.truncate (0);
       scan->ok = true;
 
       if (!dc_scan_list (scan, code->block->next))
@@ -11694,6 +11739,47 @@ dc_scan_body (gfc_code *code, dc_scan *scan)
 }
 
 
+/* True if the DO CONCURRENT construct whose body SCAN describes can be
+   offloaded.  A PURE, ELEMENTAL or declare target procedure may itself
+   run on the device, where a nested target construct does not run its
+   body (libgomp/config/gcn/target.c), so constructs in it run on the
+   host; and a procedure that the body calls would have to be available on
+   the device.  Conditional lastprivate is not allowed on DISTRIBUTE.  */
+
+static bool
+dc_device_ok (dc_scan *scan)
+{
+  gfc_symbol *proc = NULL;
+  for (gfc_namespace *ns = gfc_current_ns; ns && !proc; ns = ns->parent)
+    if (ns->proc_name && ns->proc_name->attr.flavor == FL_PROCEDURE)
+      proc = ns->proc_name;
+
+  if (proc
+      && (proc->attr.pure || proc->attr.implicit_pure
+	  || proc->attr.elemental || proc->attr.omp_declare_target))
+    return false;
+
+  if (scan->device_bad || scan->calls || scan->internal_calls)
+    return false;
+
+  for (int i = 0; i < LOCALITY_NUM; i++)
+    for (gfc_expr_list *el = scan->dc->ext.concur.locality[i];
+	 el; el = el->next)
+      if (el->expr->expr_type == EXPR_VARIABLE
+	  && !dc_device_var_ok (el->expr->symtree->n.sym))
+	return false;
+
+  for (gfc_symbol *sym : scan->order)
+    {
+      dc_use *use = scan->uses.get (sym);
+      if (use->defined && !use->udef)
+	return false;
+    }
+
+  return true;
+}
+
+
 
 /* State of the search for a branch into a DO CONCURRENT construct.  */
 
@@ -11858,6 +11944,10 @@ gfc_dc_omp_lowering (gfc_code *code)
   if (dc_branch_into (code))
     return GFC_DC_OMP_NONE;
 
+  if (flag_do_concurrent_to_openmp == GFC_DC_OMP_DEVICE
+      && dc_device_ok (&scan))
+    return GFC_DC_OMP_DEVICE;
+
   return GFC_DC_OMP_HOST;
 }
 
@@ -11942,6 +12032,18 @@ dc_namelist_from_reduce (gfc_expr_list *list)
 }
 
 
+/* True if a target construct that references SYM maps it implicitly
+   rather than making it firstprivate.  */
+
+static bool
+dc_mapped_implicitly (gfc_symbol *sym)
+{
+  tree decl = gfc_trans_omp_variable (sym, false);
+  return (gfc_omp_allocatable_p (decl) || gfc_omp_scalar_target_p (decl)
+	  || !gfc_omp_scalar_p (decl, false));
+}
+
+
 /* Build the gfc_omp_clauses of the OpenMP loop for CODE, whose body SCAN
    describes.  F2018 C1123 forbids a concurrent-limit or concurrent-step
    from referencing an index-name of the same construct, so the nest is
@@ -11953,10 +12055,20 @@ dc_namelist_from_reduce (gfc_expr_list *list)
    needs a copy per iteration, but keeps the value from the one iteration
    that defines it, or its value if none does (F2018 11.1.7.5):
    conditional lastprivate.  Without the modifier, its value would be
-   unspecified after a construct without iterations.  */
+   unspecified after a construct without iterations.  DISTRIBUTE does
+   not allow the modifier, so on a device every iteration must define the
+   variable (see dc_device_ok), and gfc_trans_omp_do_concurrent skips a
+   construct without iterations.
+
+   If DEVICE, the variables that the body defines in place are mapped
+   tofrom: OpenMP makes scalars firstprivate on a target construct by
+   default, and a SHARED one too.  What the body does not define, and the
+   outer variable of a LOCAL_INIT spec, is mapped to: it needs no copying
+   back, and its storage may be read-only, as that of a constant actual
+   argument is.  */
 
 static gfc_omp_clauses *
-dc_build_clauses (gfc_code *code, dc_scan *scan, int collapse)
+dc_build_clauses (gfc_code *code, dc_scan *scan, int collapse, bool device)
 {
   gfc_omp_clauses *clauses = gfc_get_omp_clauses ();
 
@@ -11978,10 +12090,37 @@ dc_build_clauses (gfc_code *code, dc_scan *scan, int collapse)
       *lp = gfc_get_omp_namelist ();
       (*lp)->sym = sym;
       (*lp)->where = code->loc;
-      (*lp)->u.lastprivate_conditional = true;
+      (*lp)->u.lastprivate_conditional = !device;
       lp = &(*lp)->next;
     }
 
+  if (device)
+    {
+      gfc_omp_namelist **mp = &clauses->lists[OMP_LIST_MAP];
+      auto add_map = [&] (gfc_symbol *sym, locus *where, bool defined)
+	{
+	  *mp = gfc_get_omp_namelist ();
+	  (*mp)->sym = sym;
+	  (*mp)->where = *where;
+	  (*mp)->u.map.op = defined ? OMP_MAP_TOFROM : OMP_MAP_TO;
+	  mp = &(*mp)->next;
+	};
+      for (gfc_expr_list *el = code->ext.concur.locality[LOCALITY_SHARED];
+	   el; el = el->next)
+	add_map (el->expr->symtree->n.sym, &el->expr->where,
+		 scan->defined.contains (el->expr->symtree->n.sym));
+      for (gfc_expr_list *el = code->ext.concur.locality[LOCALITY_LOCAL_INIT];
+	   el; el = el->next)
+	if (dc_mapped_implicitly (el->expr->symtree->n.sym))
+	  add_map (el->expr->symtree->n.sym, &el->expr->where, false);
+      for (gfc_symbol *sym : scan->part_defs)
+	if (!dc_locality_known (scan, sym))
+	  add_map (sym, &code->loc, true);
+      for (gfc_symbol *sym : scan->order)
+	if (!scan->defined.contains (sym) && dc_mapped_implicitly (sym))
+	  add_map (sym, &code->loc, false);
+    }
+
   return clauses;
 }
 
@@ -12006,10 +12145,54 @@ dc_retarget_cycle (gfc_code *c, gfc_code *from, gfc_code *to)
 }
 
 
-/* Translate the DO CONCURRENT construct CODE into an OpenMP loop.  */
+/* Return a condition that the DO CONCURRENT construct CODE has
+   iterations, adding the evaluation of its limits and steps to BLOCK.
+   Evaluating them again is harmless, as they may reference only pure
+   procedures (F2018 C1139).  */
+
+static tree
+dc_has_iterations (gfc_code *code, stmtblock_t *block)
+{
+  tree cond = boolean_true_node;
+
+  for (gfc_forall_iterator *fa = code->ext.concur.forall_iterator;
+       fa; fa = fa->next)
+    {
+      tree type = gfc_typenode_for_spec (&fa->var->symtree->n.sym->ts);
+      tree val[3];
+      gfc_expr *e[3] = { fa->start, fa->end, fa->stride };
+
+      for (int i = 0; i < 3; i++)
+	{
+	  gfc_se se;
+	  gfc_init_se (&se, NULL);
+	  gfc_conv_expr_val (&se, e[i]);
+	  gfc_add_block_to_block (block, &se.pre);
+	  val[i] = gfc_evaluate_now (fold_convert (type, se.expr), block);
+	  gfc_add_block_to_block (block, &se.post);
+	}
+
+      tree up = fold_build2_loc (input_location, LE_EXPR, logical_type_node,
+				 val[0], val[1]);
+      tree down = fold_build2_loc (input_location, GE_EXPR,
+				   logical_type_node, val[0], val[1]);
+      tree pos = fold_build2_loc (input_location, GT_EXPR, logical_type_node,
+				  val[2], build_zero_cst (type));
+      tree c = fold_build3_loc (input_location, COND_EXPR, logical_type_node,
+				pos, up, down);
+      cond = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
+			      logical_type_node, cond, c);
+    }
+
+  return cond;
+}
+
+
+/* Translate the DO CONCURRENT construct CODE into an OpenMP loop on the
+   host, or on a device if KIND is GFC_DC_OMP_DEVICE.  */
 
 tree
-gfc_trans_omp_do_concurrent (gfc_code *code)
+gfc_trans_omp_do_concurrent (gfc_code *code, enum gfc_dc_to_omp kind)
 {
   gfc_forall_iterator *fa;
   gfc_code *par, *iter, *inner = NULL, *first = NULL;
@@ -12077,16 +12260,34 @@ gfc_trans_omp_do_concurrent (gfc_code *code)
   dc_retarget_cycle (code->block->next, code, iter);
 
   /* 'parallel do simd': the SIMD part keeps the vectorization that the
-     serial lowering gets from its implicit IVDEP annotation.  */
-  par = gfc_get_code (EXEC_OMP_PARALLEL_DO_SIMD);
+     serial lowering gets from its implicit IVDEP annotation.  On a
+     device, the same under 'target teams distribute'.  */
+  bool device = kind == GFC_DC_OMP_DEVICE;
+  gfc_exec_op op = (device ? EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD
+		    : EXEC_OMP_PARALLEL_DO_SIMD);
+
+  par = gfc_get_code (op);
   par->loc = code->loc;
-  par->ext.omp_clauses = dc_build_clauses (code, &scan, collapse);
-  par->block = gfc_get_code (EXEC_OMP_PARALLEL_DO_SIMD);
+  par->ext.omp_clauses = dc_build_clauses (code, &scan, collapse, device);
+  par->block = gfc_get_code (op);
   par->block->loc = code->loc;
   par->block->next = first;
 
   gfc_omp_construct_depth++;
-  stmt = gfc_trans_omp_parallel_do_simd (par, NULL, NULL);
+  if (device)
+    {
+      stmt = gfc_trans_omp_target (par);
+      omp_requires_mask
+	= (enum omp_requires) (omp_requires_mask
+			       | int (OMP_REQUIRES_TARGET_USED));
+
+      /* See dc_build_clauses.  */
+      if (par->ext.omp_clauses->lists[OMP_LIST_LASTPRIVATE])
+	stmt = build3_v (COND_EXPR, dc_has_iterations (code, &block), stmt,
+			 build_empty_stmt (input_location));
+    }
+  else
+    stmt = gfc_trans_omp_parallel_do_simd (par, NULL, NULL);
   gfc_omp_construct_depth--;
   gfc_add_expr_to_block (&block, stmt);
 
diff --git a/gcc/fortran/trans-stmt.cc b/gcc/fortran/trans-stmt.cc
index 10903505cac..ef49446d98d 100644
--- a/gcc/fortran/trans-stmt.cc
+++ b/gcc/fortran/trans-stmt.cc
@@ -5785,8 +5785,9 @@ tree gfc_trans_do_concurrent (gfc_code * code)
   if (code->ext.concur.forall_iterator == NULL)
     return gfc_trans_do_concurrent_iteration (code);
 
-  if (gfc_dc_omp_lowering (code) != GFC_DC_OMP_NONE)
-    return gfc_trans_omp_do_concurrent (code);
+  enum gfc_dc_to_omp kind = gfc_dc_omp_lowering (code);
+  if (kind != GFC_DC_OMP_NONE)
+    return gfc_trans_omp_do_concurrent (code, kind);
 
   return gfc_trans_forall_1 (code, NULL);
 }
diff --git a/gcc/fortran/trans.h b/gcc/fortran/trans.h
index c6b360ce2e6..3a64da41ab0 100644
--- a/gcc/fortran/trans.h
+++ b/gcc/fortran/trans.h
@@ -859,7 +859,7 @@ struct gimplify_omp_ctx;
 void gfc_omp_firstprivatize_type_sizes (struct gimplify_omp_ctx *, tree);
 extern int gfc_omp_construct_depth;
 enum gfc_dc_to_omp gfc_dc_omp_lowering (gfc_code *);
-tree gfc_trans_omp_do_concurrent (gfc_code *);
+tree gfc_trans_omp_do_concurrent (gfc_code *, enum gfc_dc_to_omp);
 
 /* In trans-intrinsic.cc.  */
 void gfc_conv_intrinsic_mvbits (gfc_se *, gfc_actual_arglist *,
diff --git a/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_16.f90 b/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_16.f90
new file mode 100644
index 00000000000..4470ce27b2c
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_16.f90
@@ -0,0 +1,38 @@
+! { dg-do compile }
+! { dg-additional-options "-fdo-concurrent-to-openmp=device -fdump-tree-original" }
+!
+! PR 128590
+
+module m
+contains
+  subroutine assumed_type (x, b, n)
+    type(*), intent(in) :: x(:)
+    integer :: n, b(n), i
+    do concurrent (i = 1:n)
+      b(i) = size (x) + i
+    end do
+  end subroutine
+
+  subroutine local_init (c, b)
+    integer :: c(4), b(100), i
+    do concurrent (i = 1:100) local_init(c)
+      c(1) = i
+      b(i) = sum (c)
+    end do
+  end subroutine
+
+  function pointer_result (n)
+    integer, intent(in) :: n
+    integer, pointer :: pointer_result(:)
+    integer :: i
+    allocate (pointer_result(n))
+    do concurrent (i = 1:n)
+      pointer_result(i) = i
+    end do
+  end function
+end module m
+
+! Only the loop of local_init is offloaded.
+! { dg-final { scan-tree-dump-times "#pragma omp target" 1 "original" } }
+! { dg-final { scan-tree-dump-times "#pragma omp parallel" 3 "original" } }
+! { dg-final { scan-tree-dump "target map\\(to:\\*c\\)" "original" } }
diff --git a/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_6.f90 b/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_6.f90
new file mode 100644
index 00000000000..39bd161e2b2
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_6.f90
@@ -0,0 +1,100 @@
+! { dg-do compile }
+! { dg-additional-options "-fdo-concurrent-to-openmp=device -fdump-tree-original" }
+! PR 128590
+!
+! -fdo-concurrent-to-openmp=device lowers DO CONCURRENT to 'target teams
+! distribute parallel do simd'.  Scalars that the body defines in place
+! are mapped tofrom, since a target construct otherwise makes them
+! firstprivate.  The DO variable of a loop in a BLOCK construct is
+! defined by every iteration, so plain lastprivate gives it its value.
+
+subroutine offloaded (a, b, n)
+  integer :: n, i
+  real :: a(n), b(n)
+  do concurrent (i = 1:n)
+     b(i) = sqrt (a(i))
+  end do
+end subroutine offloaded
+
+subroutine collapsed (c, m)
+  integer :: m, i, j
+  real, allocatable :: c(:,:)
+  do concurrent (i = 1:m, j = 1:m)
+     c(i,j) = real(i) * real(j)
+  end do
+end subroutine collapsed
+
+subroutine with_locality (a, n, s, flag)
+  integer :: n, i, t
+  real :: a(n), s
+  logical :: flag
+  do concurrent (i = 1:n) reduce(+:s) shared(flag) local(t)
+     t = 2 * i
+     s = s + a(i) * real(t)
+     if (a(i) < 0.0) flag = .true.
+  end do
+end subroutine with_locality
+
+subroutine temp_lastprivate (a, b, n)
+  integer :: n, i
+  real :: a(n), b(n), t
+  do concurrent (i = 1:n)
+     t = a(i) + 1.0
+     b(i) = t * t
+  end do
+end subroutine temp_lastprivate
+
+subroutine char_part (s, n)
+  integer :: n, i
+  character(len=100) :: s
+  do concurrent (i = 1:n)
+     s(i:i) = 'x'
+  end do
+end subroutine char_part
+
+subroutine in_target_data (a, n)
+  integer :: n, i, k
+  real :: a(n)
+  !$omp target data map(tofrom: a)
+  do k = 1, 10
+     do concurrent (i = 1:n)
+        a(i) = a(i) + 1.0
+     end do
+  end do
+  !$omp end target data
+end subroutine in_target_data
+
+subroutine do_in_block (a, b, n)
+  integer :: n, i, jb
+  real :: a(n), b(n)
+  do concurrent (i = 1:n)
+     block
+       do jb = 1, 3
+          b(i) = b(i) + a(i) * jb
+       end do
+     end block
+  end do
+end subroutine do_in_block
+
+subroutine read_only (a, x, y, str)
+  real :: a(:)
+  real, intent(in) :: x(:), y
+  character(len=*), intent(in) :: str
+  integer :: i
+  do concurrent (i = 1:size (a)) shared(x, y)
+     if (str(1:1) == 'a') a(i) = x(i) + y
+  end do
+end subroutine read_only
+
+! { dg-final { scan-tree-dump-times "#pragma omp target" 9 "original" } }
+! { dg-final { scan-tree-dump-times "#pragma omp target data" 1 "original" } }
+! { dg-final { scan-tree-dump-times "#pragma omp teams" 8 "original" } }
+! { dg-final { scan-tree-dump-times "#pragma omp distribute" 8 "original" } }
+! { dg-final { scan-tree-dump-times "#pragma omp simd" 8 "original" } }
+! { dg-final { scan-tree-dump-times "collapse\\(2\\)" 3 "original" } }
+! { dg-final { scan-tree-dump "target map\\(tofrom:\\*flag\\)" "original" } }
+! { dg-final { scan-tree-dump "map\\(tofrom:\\*s\\) map\\(alloc:s \\\[pointer assign, bias: 0\\\]\\)\n" "original" } }
+! { dg-final { scan-tree-dump "target map\\(to:\\*a\\) map\\(alloc:a \\\[pointer assign, bias: 0\\\]\\) map\\(tofrom:t\\)" "original" } }
+! { dg-final { scan-tree-dump "target map\\(to:\[^\n\r\]*x\\.0\[^\n\r\]* map\\(to:\\*y\\) map\\(alloc:y \\\[pointer assign, bias: 0\\\]\\) map\\(to:\\*str\\)" "original" } }
+! { dg-final { scan-tree-dump "distribute lastprivate\\(t\\)" "original" } }
+! { dg-final { scan-tree-dump "distribute lastprivate\\(jb\\)" "original" } }
diff --git a/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_7.f90 b/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_7.f90
new file mode 100644
index 00000000000..6535a7986f6
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/gomp/do_concurrent_to_openmp_7.f90
@@ -0,0 +1,90 @@
+! { dg-do compile }
+! { dg-additional-options "-fdo-concurrent-to-openmp=device -fdump-tree-original" }
+! PR 128590
+!
+! DO CONCURRENT constructs that -fdo-concurrent-to-openmp=device lowers to
+! a host 'parallel do simd' instead.  Conditional lastprivate, which a
+! variable defined by some iterations needs, is not allowed on DISTRIBUTE;
+! a called procedure would have to be available on the device; an
+! assumed-size array cannot be mapped implicitly, nor a pointer without
+! attaching it; and in a PURE procedure, which may itself be compiled for
+! the device, a nested target construct would not run its body.  A
+! definition after a GOTO or after an EXIT from a BLOCK construct may be
+! skipped, so it is conditional too.
+
+module m
+  implicit none
+contains
+  pure real function f (x)
+    real, intent(in) :: x
+    f = x + 1.0
+  end function f
+
+  pure subroutine in_pure (a, n)
+    integer, intent(in) :: n
+    real, intent(inout) :: a(n)
+    integer :: i
+    do concurrent (i = 1:n)
+       a(i) = a(i) * 2.0
+    end do
+  end subroutine in_pure
+end module m
+
+subroutine conditional_def (a, n, key, idx)
+  integer :: n, i, idx
+  real :: a(n), key
+  do concurrent (i = 1:n)
+     if (a(i) == key) idx = i
+  end do
+end subroutine conditional_def
+
+subroutine calls_proc (a, b, n)
+  use m
+  integer :: n, i
+  real :: a(n), b(n)
+  do concurrent (i = 1:n)
+     b(i) = f (a(i))
+  end do
+end subroutine calls_proc
+
+subroutine assumed_size (a, n)
+  integer :: n, i
+  real :: a(*)
+  do concurrent (i = 1:n)
+     a(i) = 0.0
+  end do
+end subroutine assumed_size
+
+subroutine pointer_array (p, n)
+  integer :: n, i
+  real, pointer :: p(:)
+  do concurrent (i = 1:n)
+     p(i) = 0.0
+  end do
+end subroutine pointer_array
+
+subroutine skipped_by_goto (a, n, x)
+  integer :: n, i, x
+  real :: a(n)
+  do concurrent (i = 1:n)
+     a(i) = 0.0
+     if (i /= 5) goto 10
+     x = 3
+10   continue
+  end do
+end subroutine skipped_by_goto
+
+subroutine skipped_by_exit (a, n, x)
+  integer :: n, i, x
+  real :: a(n)
+  do concurrent (i = 1:n)
+     a(i) = 0.0
+     blk: block
+       if (i /= 7) exit blk
+       x = 7
+     end block blk
+  end do
+end subroutine skipped_by_exit
+
+! { dg-final { scan-tree-dump-not "#pragma omp target" "original" } }
+! { dg-final { scan-tree-dump-times "#pragma omp parallel" 7 "original" } }
diff --git a/libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_4.f90 b/libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_4.f90
new file mode 100644
index 00000000000..c169ea1a9c0
--- /dev/null
+++ b/libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_4.f90
@@ -0,0 +1,138 @@
+! { dg-do run }
+! { dg-additional-options "-fdo-concurrent-to-openmp=device" }
+! PR 128590
+!
+! DO CONCURRENT constructs lowered to offloaded OpenMP loops.  Results
+! must not depend, beyond rounding, on whether the loops run on a device
+! or on the host.
+! A scalar that the body defines in place, here a SHARED flag and a
+! character substring, must come back from the device.
+
+module data
+  implicit none
+  real, allocatable :: g(:)
+end module data
+
+program main
+  use data
+  implicit none
+  integer, parameter :: n = 100000, m = 300
+  integer :: i, j, k, t
+  real, allocatable :: a(:), b(:), c(:,:)
+  real :: s, rmax, tmp
+  logical :: flag
+  character(len=64) :: str
+
+  allocate (a(n), b(n), c(m,m), g(n))
+  do i = 1, n
+     a(i) = real(mod(i, 1000)) / 10.0
+  end do
+
+  do concurrent (i = 1:n)
+     b(i) = 2.0 * a(i) + sqrt (a(i))
+  end do
+  do j = 1, n
+     if (abs (b(j) - (2.0 * a(j) + sqrt (a(j)))) > 1.0e-6 * abs (b(j))) stop 1
+  end do
+
+  do concurrent (i = 1:m, j = 1:m)
+     c(i,j) = real(i) - real(j)
+  end do
+  do j = 1, m
+     do i = 1, m
+        if (c(i,j) /= real(i) - real(j)) stop 2
+     end do
+  end do
+
+  s = 1.0
+  rmax = -1.0
+  do concurrent (i = 1:1000) reduce(+:s) reduce(max:rmax)
+     s = s + a(i)
+     rmax = max (rmax, a(i))
+  end do
+  if (abs (s - (1.0 + sum (a(1:1000)))) > 1.0e-5 * s) stop 3
+  if (rmax /= maxval (a(1:1000))) stop 4
+
+  flag = .false.
+  do concurrent (i = 1:n) shared(flag)
+     if (a(i) > 99.85) flag = .true.
+  end do
+  if (.not. flag) stop 5
+
+  t = 5
+  do concurrent (i = 1:n) local(k) local_init(t)
+     k = i + t
+     t = -1
+     b(i) = real(k)
+  end do
+  if (t /= 5) stop 6
+  do j = 1, n
+     if (b(j) /= real(j + 5)) stop 7
+  end do
+
+  do concurrent (i = n:n)
+     tmp = a(i) + 1.0
+     b(i) = tmp
+  end do
+  if (tmp /= a(n) + 1.0) stop 8
+
+  tmp = -2.0
+  k = -3
+  do concurrent (i = 1:n-n)
+     tmp = a(i) + 1.0
+     b(i) = tmp
+  end do
+  if (tmp /= -2.0) stop 13
+
+  str = ''
+  do concurrent (i = 1:len (str))
+     str(i:i) = achar (iachar ('a') + mod (i - 1, 26))
+  end do
+  if (str(1:3) /= 'abc' .or. str(27:28) /= 'ab') stop 9
+
+  g = 0.0
+  do concurrent (i = 1:n)
+     g(i) = a(i)
+  end do
+  if (any (g /= a)) stop 10
+
+  b = 0.0
+  !$omp target data map(tofrom: b) map(to: a)
+  do k = 1, 5
+     do concurrent (i = 1:n)
+        if (a(i) < 1.0) cycle
+        b(i) = b(i) + a(i)
+     end do
+  end do
+  !$omp end target data
+  do j = 1, n
+     if (a(j) < 1.0) then
+        if (b(j) /= 0.0) stop 11
+     else if (abs (b(j) - 5.0 * a(j)) > 1.0e-6 * b(j)) then
+        stop 12
+     end if
+  end do
+
+  ! The DO variable of a loop in a BLOCK construct.
+  b = 0.0
+  do concurrent (i = 1:n)
+     block
+       do k = 1, 3
+          b(i) = b(i) + a(i) * k
+       end do
+     end block
+  end do
+  do j = 1, n
+     if (abs (b(j) - 6.0 * a(j)) > 1.0e-6 * b(j)) stop 14
+  end do
+
+  ! Only one iteration reaches the definition after the GOTO.
+  t = -1
+  do concurrent (i = 1:n)
+     b(i) = a(i)
+     if (i /= 5) goto 20
+     t = i
+20   continue
+  end do
+  if (t /= 5) stop 15
+end program main
diff --git a/libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_5.f90 b/libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_5.f90
new file mode 100644
index 00000000000..095f98f381f
--- /dev/null
+++ b/libgomp/testsuite/libgomp.fortran/do_concurrent_to_openmp_5.f90
@@ -0,0 +1,77 @@
+! { dg-do run { target offload_device } }
+! { dg-additional-options "-fdo-concurrent-to-openmp=device" }
+! { dg-set-target-env-var OMP_TARGET_OFFLOAD "mandatory" }
+! PR 128590
+!
+! With offloading mandatory, DO CONCURRENT constructs lowered to target
+! regions must run on the device, and data must come back from it.
+! Data that the body only reads must not be copied back: here it is
+! constant actual arguments, which may be in read-only storage.
+
+module consts
+  implicit none
+  type pair
+     real :: u, v
+  end type pair
+contains
+  subroutine use_consts (a, x, y, str, p, z, w)
+    real, intent(inout) :: a(:)
+    real, intent(in) :: x(:), y
+    character(len=*), intent(in) :: str
+    type(pair), intent(in) :: p
+    real, intent(in), optional :: z
+    real, intent(in), target :: w
+    integer :: i
+    do concurrent (i = 1:size (a)) shared(x, y)
+       a(i) = a(i) * x(i) + y + p%u + w
+       if (str(2:2) == 'b') a(i) = a(i) + 1.0
+       if (present (z)) a(i) = a(i) + z
+    end do
+  end subroutine use_consts
+end module consts
+
+program main
+  use consts
+  implicit none
+  integer, parameter :: n = 4096
+  integer :: i, j
+  real :: a(n), b(n), s
+  logical :: flag
+
+  do concurrent (i = 1:n)
+     a(i) = real(i)
+  end do
+  do j = 1, n
+     if (a(j) /= real(j)) stop 1
+  end do
+
+  s = 0.0
+  do concurrent (i = 1:n) reduce(+:s)
+     s = s + 1.0
+  end do
+  if (s /= real(n)) stop 2
+
+  flag = .false.
+  do concurrent (i = 1:n) shared(flag)
+     if (i == 1234) flag = .true.
+  end do
+  if (.not. flag) stop 3
+
+  !$omp target data map(to: a) map(from: b)
+  do concurrent (i = 1:n)
+     b(i) = 2.0 * a(i)
+  end do
+  !$omp end target data
+  do j = 1, n
+     if (b(j) /= 2.0 * real(j)) stop 4
+  end do
+
+  a = 1.0
+  call use_consts (a, [(2.0, i = 1, n)], 1.0, 'abc', pair (0.5, 0.0), &
+                   0.25, 0.125)
+  if (any (a /= 4.875)) stop 5
+  a = 1.0
+  call use_consts (a, [(2.0, i = 1, n)], 1.0, 'abc', pair (0.5, 0.0), &
+                   w=0.125)
+  if (any (a /= 4.625)) stop 6
+end program main
-- 
2.56.1

Reply via email to