Skip to content

Commit fa459d9

Browse files
committed
[flang] Rewrite "1*j" to "(j)", not "j", when j is a variable
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 llvm/llvm-project#63259. Differential Revision: https://reviews.llvm.org/D153457
1 parent 73a0ae0 commit fa459d9

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

flang/lib/Evaluate/fold-implementation.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1764,7 +1764,12 @@ Expr<T> FoldOperation(FoldingContext &context, Negate<T> &&x) {
17641764
}
17651765
auto &operand{x.left()};
17661766
if (auto *nn{std::get_if<Negate<T>>(&x.left().u)}) {
1767-
return std::move(nn->left()); // -(-x) -> x
1767+
// -(-x) -> (x)
1768+
if (IsVariable(nn->left())) {
1769+
return FoldOperation(context, Parentheses<T>{std::move(nn->left())});
1770+
} else {
1771+
return std::move(nn->left());
1772+
}
17681773
} else if (auto value{GetScalarConstantValue<T>(operand)}) {
17691774
if constexpr (T::category == TypeCategory::Integer) {
17701775
auto negated{value->Negate()};
@@ -1883,9 +1888,13 @@ Expr<T> FoldOperation(FoldingContext &context, Multiply<T> &&x) {
18831888
if (c->IsZero()) {
18841889
return std::move(x.left());
18851890
} else if (c->CompareSigned(Scalar<T>{1}) == Ordering::Equal) {
1886-
return std::move(x.right());
1891+
if (IsVariable(x.right())) {
1892+
return FoldOperation(context, Parentheses<T>{std::move(x.right())});
1893+
} else {
1894+
return std::move(x.right());
1895+
}
18871896
} else if (c->CompareSigned(Scalar<T>{-1}) == Ordering::Equal) {
1888-
return Expr<T>{Negate<T>{std::move(x.right())}};
1897+
return FoldOperation(context, Negate<T>{std::move(x.right())});
18891898
}
18901899
}
18911900
}

flang/test/Evaluate/rewrite04.f90

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
! RUN: %flang_fc1 -fdebug-unparse %s 2>&1 | FileCheck %s
2+
! Ensure folding of 1*j is a parenthesized (j) when j is a variable.
3+
call foo(1*j)
4+
!CHECK: CALL foo((j))
5+
end

0 commit comments

Comments
 (0)