[flang-commits] [flang] [flang] Fix folding of SHAPE(SPREAD(source, dim, ncopies=-1)) (PR #141146)

Peter Klausler via flang-commits flang-commits at lists.llvm.org
Thu May 22 14:48:44 PDT 2025


https://github.com/klausler created https://github.com/llvm/llvm-project/pull/141146

The number of copies on the new dimension must be clamped via MAX(0, ncopies) so that it is no less than zero.

Fixes https://github.com/llvm/llvm-project/issues/141119.

>From 7e8e7651a6e0afb934078ba3fac8589312ac457e Mon Sep 17 00:00:00 2001
From: Peter Klausler <pklausler at nvidia.com>
Date: Thu, 22 May 2025 14:45:34 -0700
Subject: [PATCH] [flang] Fix folding of SHAPE(SPREAD(source,dim,ncopies=-1))

The number of copies on the new dimension must be clamped via
MAX(0, ncopies) so that it is no less than zero.

Fixes https://github.com/llvm/llvm-project/issues/141119.
---
 flang/lib/Evaluate/shape.cpp        | 7 ++++---
 flang/test/Evaluate/fold-spread.f90 | 1 +
 2 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/flang/lib/Evaluate/shape.cpp b/flang/lib/Evaluate/shape.cpp
index ac4811e9978eb..776866d1416d2 100644
--- a/flang/lib/Evaluate/shape.cpp
+++ b/flang/lib/Evaluate/shape.cpp
@@ -1073,8 +1073,8 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
         }
       }
     } else if (intrinsic->name == "spread") {
-      // SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with NCOPIES inserted
-      // at position DIM.
+      // SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with MAX(0,NCOPIES)
+      // inserted at position DIM.
       if (call.arguments().size() == 3) {
         auto arrayShape{
             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
@@ -1086,7 +1086,8 @@ auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
             if (*dim >= 1 &&
                 static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {
               arrayShape->emplace(arrayShape->begin() + *dim - 1,
-                  ConvertToType<ExtentType>(common::Clone(*nCopies)));
+                  Extremum<SubscriptInteger>{Ordering::Greater, ExtentExpr{0},
+                      ConvertToType<ExtentType>(common::Clone(*nCopies))});
               return std::move(*arrayShape);
             }
           }
diff --git a/flang/test/Evaluate/fold-spread.f90 b/flang/test/Evaluate/fold-spread.f90
index b7e493ee061c8..c8b87e8c87811 100644
--- a/flang/test/Evaluate/fold-spread.f90
+++ b/flang/test/Evaluate/fold-spread.f90
@@ -12,4 +12,5 @@ module m1
   logical, parameter :: test_log4 = all(any(spread([.false., .true.], 2, 2), dim=2) .eqv. [.false., .true.])
   logical, parameter :: test_m2toa3 = all(spread(reshape([(j,j=1,6)],[2,3]),1,4) == &
                                           reshape([((j,k=1,4),j=1,6)],[4,2,3]))
+  logical, parameter :: test_shape_neg = all(shape(spread(0,1,-1)) == [0])
 end module



More information about the flang-commits mailing list