diff --git a/flang/lib/Evaluate/fold-implementation.h b/flang/lib/Evaluate/fold-implementation.h index ad18d7ed83b1b..50e9b3bc22cfa 100644 --- a/flang/lib/Evaluate/fold-implementation.h +++ b/flang/lib/Evaluate/fold-implementation.h @@ -1764,7 +1764,12 @@ Expr FoldOperation(FoldingContext &context, Negate &&x) { } auto &operand{x.left()}; if (auto *nn{std::get_if>(&x.left().u)}) { - return std::move(nn->left()); // -(-x) -> x + // -(-x) -> (x) + if (IsVariable(nn->left())) { + return FoldOperation(context, Parentheses{std::move(nn->left())}); + } else { + return std::move(nn->left()); + } } else if (auto value{GetScalarConstantValue(operand)}) { if constexpr (T::category == TypeCategory::Integer) { auto negated{value->Negate()}; @@ -1883,9 +1888,13 @@ Expr FoldOperation(FoldingContext &context, Multiply &&x) { if (c->IsZero()) { return std::move(x.left()); } else if (c->CompareSigned(Scalar{1}) == Ordering::Equal) { - return std::move(x.right()); + if (IsVariable(x.right())) { + return FoldOperation(context, Parentheses{std::move(x.right())}); + } else { + return std::move(x.right()); + } } else if (c->CompareSigned(Scalar{-1}) == Ordering::Equal) { - return Expr{Negate{std::move(x.right())}}; + return FoldOperation(context, Negate{std::move(x.right())}); } } } diff --git a/flang/test/Evaluate/rewrite04.f90 b/flang/test/Evaluate/rewrite04.f90 new file mode 100644 index 0000000000000..220be291c3f2c --- /dev/null +++ b/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