[flang-commits] [PATCH] D153457: [flang] Rewrite "1*j" to "(j)", not "j", when j is a variable

Peter Klausler via Phabricator via flang-commits flang-commits at lists.llvm.org
Wed Jun 21 12:47:52 PDT 2023


klausler created this revision.
klausler added a reviewer: PeteSteinfeld.
klausler added a project: Flang.
Herald added subscribers: sunshaoce, jdoerfert.
Herald added a reviewer: sscalpone.
Herald added a project: All.
klausler requested review of this revision.

Expression folding currently unconditionally rewrites "1*j"
to "j", which is wrong when "j" is a variable, as it transforms
an expression into a variable and can lead to incorrect associations
in contexts like an actual argument or an ASSOCIATE selector.   
Transform "1*j" to a parenthesized "(j)" when "j" is a variable. 
Fixes LLVM bug https://github.com/llvm/llvm-project/issues/63259.


https://reviews.llvm.org/D153457

Files:
  flang/lib/Evaluate/fold-implementation.h
  flang/test/Evaluate/rewrite04.f90


Index: flang/test/Evaluate/rewrite04.f90
===================================================================
--- /dev/null
+++ flang/test/Evaluate/rewrite04.f90
@@ -0,0 +1,5 @@
+! RUN: %flang_fc1 -fdebug-unparse %s 2>&1 | FileCheck %s
+! Ensure folding of 1*j is a parenthesized (j) when j is a variable.
+call foo(1*j)
+!CHECK: CALL foo((j))
+end
Index: flang/lib/Evaluate/fold-implementation.h
===================================================================
--- flang/lib/Evaluate/fold-implementation.h
+++ flang/lib/Evaluate/fold-implementation.h
@@ -1761,7 +1761,12 @@
   }
   auto &operand{x.left()};
   if (auto *nn{std::get_if<Negate<T>>(&x.left().u)}) {
-    return std::move(nn->left()); // -(-x) -> x
+    // -(-x) -> (x)
+    if (IsVariable(nn->left())) {
+      return FoldOperation(context, Parentheses<T>{std::move(nn->left())});
+    } else {
+      return std::move(nn->left());
+    }
   } else if (auto value{GetScalarConstantValue<T>(operand)}) {
     if constexpr (T::category == TypeCategory::Integer) {
       auto negated{value->Negate()};
@@ -1880,9 +1885,13 @@
       if (c->IsZero()) {
         return std::move(x.left());
       } else if (c->CompareSigned(Scalar<T>{1}) == Ordering::Equal) {
-        return std::move(x.right());
+        if (IsVariable(x.right())) {
+          return FoldOperation(context, Parentheses<T>{std::move(x.right())});
+        } else {
+          return std::move(x.right());
+        }
       } else if (c->CompareSigned(Scalar<T>{-1}) == Ordering::Equal) {
-        return Expr<T>{Negate<T>{std::move(x.right())}};
+        return FoldOperation(context, Negate<T>{std::move(x.right())});
       }
     }
   }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D153457.533362.patch
Type: text/x-patch
Size: 1673 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/flang-commits/attachments/20230621/a2f42177/attachment-0001.bin>


More information about the flang-commits mailing list