| 1 |
//===-- lib/Evaluate/fold-reduction.h -------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#ifndef FORTRAN_EVALUATE_FOLD_REDUCTION_H_ |
| 10 |
#define FORTRAN_EVALUATE_FOLD_REDUCTION_H_ |
| 11 |
|
| 12 |
#include "fold-implementation.h" |
| 13 |
|
| 14 |
namespace Fortran::evaluate { |
| 15 |
|
| 16 |
// DOT_PRODUCT |
| 17 |
template <typename T> |
| 18 |
static Expr<T> FoldDotProduct( |
| 19 |
FoldingContext &context, FunctionRef<T> &&funcRef) { |
| 20 |
using Element = typename Constant<T>::Element; |
| 21 |
auto args{funcRef.arguments()}; |
| 22 |
CHECK(args.size() == 2); |
| 23 |
Folder<T> folder{context}; |
| 24 |
Constant<T> *va{folder.Folding(args[0])}; |
| 25 |
Constant<T> *vb{folder.Folding(args[1])}; |
| 26 |
if (va && vb) { |
| 27 |
CHECK(va->Rank() == 1 && vb->Rank() == 1); |
| 28 |
if (va->size() != vb->size()) { |
| 29 |
context.messages().Say( |
| 30 |
"Vector arguments to DOT_PRODUCT have distinct extents %zd and %zd"_err_en_US, |
| 31 |
va->size(), vb->size()); |
| 32 |
return MakeInvalidIntrinsic(std::move(funcRef)); |
| 33 |
} |
| 34 |
Element sum{}; |
| 35 |
bool overflow{false}; |
| 36 |
if constexpr (T::category == TypeCategory::Complex) { |
| 37 |
std::vector<Element> conjugates; |
| 38 |
for (const Element &x : va->values()) { |
| 39 |
conjugates.emplace_back(x.CONJG()); |
| 40 |
} |
| 41 |
Constant<T> conjgA{ |
| 42 |
std::move(conjugates), ConstantSubscripts{va->shape()}}; |
| 43 |
Expr<T> products{Fold( |
| 44 |
context, Expr<T>{std::move(conjgA)} * Expr<T>{Constant<T>{*vb}})}; |
| 45 |
Constant<T> &cProducts{DEREF(UnwrapConstantValue<T>(products))}; |
| 46 |
[[maybe_unused]] Element correction{}; |
| 47 |
const auto &rounding{context.targetCharacteristics().roundingMode()}; |
| 48 |
for (const Element &x : cProducts.values()) { |
| 49 |
if constexpr (useKahanSummation) { |
| 50 |
auto next{correction.Add(x, rounding)}; |
| 51 |
overflow |= next.flags.test(RealFlag::Overflow); |
| 52 |
auto added{sum.Add(next.value, rounding)}; |
| 53 |
overflow |= added.flags.test(RealFlag::Overflow); |
| 54 |
correction = added.value.Subtract(sum, rounding) |
| 55 |
.value.Subtract(next.value, rounding) |
| 56 |
.value; |
| 57 |
sum = std::move(added.value); |
| 58 |
} else { |
| 59 |
auto added{sum.Add(x, rounding)}; |
| 60 |
overflow |= added.flags.test(RealFlag::Overflow); |
| 61 |
sum = std::move(added.value); |
| 62 |
} |
| 63 |
} |
| 64 |
} else if constexpr (T::category == TypeCategory::Logical) { |
| 65 |
Expr<T> conjunctions{Fold(context, |
| 66 |
Expr<T>{LogicalOperation<T::kind>{LogicalOperator::And, |
| 67 |
Expr<T>{Constant<T>{*va}}, Expr<T>{Constant<T>{*vb}}}})}; |
| 68 |
Constant<T> &cConjunctions{DEREF(UnwrapConstantValue<T>(conjunctions))}; |
| 69 |
for (const Element &x : cConjunctions.values()) { |
| 70 |
if (x.IsTrue()) { |
| 71 |
sum = Element{true}; |
| 72 |
break; |
| 73 |
} |
| 74 |
} |
| 75 |
} else if constexpr (T::category == TypeCategory::Integer) { |
| 76 |
Expr<T> products{ |
| 77 |
Fold(context, Expr<T>{Constant<T>{*va}} * Expr<T>{Constant<T>{*vb}})}; |
| 78 |
Constant<T> &cProducts{DEREF(UnwrapConstantValue<T>(products))}; |
| 79 |
for (const Element &x : cProducts.values()) { |
| 80 |
auto next{sum.AddSigned(x)}; |
| 81 |
overflow |= next.overflow; |
| 82 |
sum = std::move(next.value); |
| 83 |
} |
| 84 |
} else { |
| 85 |
static_assert(T::category == TypeCategory::Real); |
| 86 |
Expr<T> products{ |
| 87 |
Fold(context, Expr<T>{Constant<T>{*va}} * Expr<T>{Constant<T>{*vb}})}; |
| 88 |
Constant<T> &cProducts{DEREF(UnwrapConstantValue<T>(products))}; |
| 89 |
[[maybe_unused]] Element correction{}; |
| 90 |
const auto &rounding{context.targetCharacteristics().roundingMode()}; |
| 91 |
for (const Element &x : cProducts.values()) { |
| 92 |
if constexpr (useKahanSummation) { |
| 93 |
auto next{correction.Add(x, rounding)}; |
| 94 |
overflow |= next.flags.test(RealFlag::Overflow); |
| 95 |
auto added{sum.Add(next.value, rounding)}; |
| 96 |
overflow |= added.flags.test(RealFlag::Overflow); |
| 97 |
correction = added.value.Subtract(sum, rounding) |
| 98 |
.value.Subtract(next.value, rounding) |
| 99 |
.value; |
| 100 |
sum = std::move(added.value); |
| 101 |
} else { |
| 102 |
auto added{sum.Add(x, rounding)}; |
| 103 |
overflow |= added.flags.test(RealFlag::Overflow); |
| 104 |
sum = std::move(added.value); |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
if (overflow && |
| 109 |
context.languageFeatures().ShouldWarn( |
| 110 |
common::UsageWarning::FoldingException)) { |
| 111 |
context.messages().Say( |
| 112 |
"DOT_PRODUCT of %s data overflowed during computation"_warn_en_US, |
| 113 |
T::AsFortran()); |
| 114 |
} |
| 115 |
return Expr<T>{Constant<T>{std::move(sum)}}; |
| 116 |
} |
| 117 |
return Expr<T>{std::move(funcRef)}; |
| 118 |
} |
| 119 |
|
| 120 |
// Fold and validate a DIM= argument. Returns false on error. |
| 121 |
bool CheckReductionDIM(std::optional<int> &dim, FoldingContext &, |
| 122 |
ActualArguments &, std::optional<int> dimIndex, int rank); |
| 123 |
|
| 124 |
// Fold and validate a MASK= argument. Return null on error, absent MASK=, or |
| 125 |
// non-constant MASK=. |
| 126 |
Constant<LogicalResult> *GetReductionMASK( |
| 127 |
std::optional<ActualArgument> &maskArg, const ConstantSubscripts &shape, |
| 128 |
FoldingContext &); |
| 129 |
|
| 130 |
// Common preprocessing for reduction transformational intrinsic function |
| 131 |
// folding. If the intrinsic can have DIM= &/or MASK= arguments, extract |
| 132 |
// and check them. If a MASK= is present, apply it to the array data and |
| 133 |
// substitute replacement values for elements corresponding to .FALSE. in |
| 134 |
// the mask. If the result is present, the intrinsic call can be folded. |
| 135 |
template <typename T> struct ArrayAndMask { |
| 136 |
Constant<T> array; |
| 137 |
Constant<LogicalResult> mask; |
| 138 |
}; |
| 139 |
template <typename T> |
| 140 |
static std::optional<ArrayAndMask<T>> ProcessReductionArgs( |
| 141 |
FoldingContext &context, ActualArguments &arg, std::optional<int> &dim, |
| 142 |
int arrayIndex, std::optional<int> dimIndex = std::nullopt, |
| 143 |
std::optional<int> maskIndex = std::nullopt) { |
| 144 |
if (arg.empty()) { |
| 145 |
return std::nullopt; |
| 146 |
} |
| 147 |
Constant<T> *folded{Folder<T>{context}.Folding(arg[arrayIndex])}; |
| 148 |
if (!folded || folded->Rank() < 1) { |
| 149 |
return std::nullopt; |
| 150 |
} |
| 151 |
if (!CheckReductionDIM(dim, context, arg, dimIndex, folded->Rank())) { |
| 152 |
return std::nullopt; |
| 153 |
} |
| 154 |
std::size_t n{folded->size()}; |
| 155 |
std::vector<Scalar<LogicalResult>> maskElement; |
| 156 |
if (maskIndex && static_cast<std::size_t>(*maskIndex) < arg.size() && |
| 157 |
arg[*maskIndex]) { |
| 158 |
if (const Constant<LogicalResult> *origMask{ |
| 159 |
GetReductionMASK(arg[*maskIndex], folded->shape(), context)}) { |
| 160 |
if (auto scalarMask{origMask->GetScalarValue()}) { |
| 161 |
maskElement = |
| 162 |
std::vector<Scalar<LogicalResult>>(n, scalarMask->IsTrue()); |
| 163 |
} else { |
| 164 |
maskElement = origMask->values(); |
| 165 |
} |
| 166 |
} else { |
| 167 |
return std::nullopt; |
| 168 |
} |
| 169 |
} else { |
| 170 |
maskElement = std::vector<Scalar<LogicalResult>>(n, true); |
| 171 |
} |
| 172 |
return ArrayAndMask<T>{Constant<T>(*folded), |
| 173 |
Constant<LogicalResult>{ |
| 174 |
std::move(maskElement), ConstantSubscripts{folded->shape()}}}; |
| 175 |
} |
| 176 |
|
| 177 |
// Generalized reduction to an array of one dimension fewer (w/ DIM=) |
| 178 |
// or to a scalar (w/o DIM=). The ACCUMULATOR type must define |
| 179 |
// operator()(Scalar<T> &, const ConstantSubscripts &, bool first) |
| 180 |
// and Done(Scalar<T> &). |
| 181 |
template <typename T, typename ACCUMULATOR, typename ARRAY> |
| 182 |
static Constant<T> DoReduction(const Constant<ARRAY> &array, |
| 183 |
const Constant<LogicalResult> &mask, std::optional<int> &dim, |
| 184 |
const Scalar<T> &identity, ACCUMULATOR &accumulator) { |
| 185 |
ConstantSubscripts at{array.lbounds()}; |
| 186 |
ConstantSubscripts maskAt{mask.lbounds()}; |
| 187 |
std::vector<typename Constant<T>::Element> elements; |
| 188 |
ConstantSubscripts resultShape; // empty -> scalar |
| 189 |
if (dim) { // DIM= is present, so result is an array |
| 190 |
resultShape = array.shape(); |
| 191 |
resultShape.erase(resultShape.begin() + (*dim - 1)); |
| 192 |
ConstantSubscript dimExtent{array.shape().at(*dim - 1)}; |
| 193 |
CHECK(dimExtent == mask.shape().at(*dim - 1)); |
| 194 |
ConstantSubscript &dimAt{at[*dim - 1]}; |
| 195 |
ConstantSubscript dimLbound{dimAt}; |
| 196 |
ConstantSubscript &maskDimAt{maskAt[*dim - 1]}; |
| 197 |
ConstantSubscript maskDimLbound{maskDimAt}; |
| 198 |
for (auto n{GetSize(resultShape)}; n-- > 0; |
| 199 |
array.IncrementSubscripts(at), mask.IncrementSubscripts(maskAt)) { |
| 200 |
elements.push_back(identity); |
| 201 |
if (dimExtent > 0) { |
| 202 |
dimAt = dimLbound; |
| 203 |
maskDimAt = maskDimLbound; |
| 204 |
bool firstUnmasked{true}; |
| 205 |
for (ConstantSubscript j{0}; j < dimExtent; ++j, ++dimAt, ++maskDimAt) { |
| 206 |
if (mask.At(maskAt).IsTrue()) { |
| 207 |
accumulator(elements.back(), at, firstUnmasked); |
| 208 |
firstUnmasked = false; |
| 209 |
} |
| 210 |
} |
| 211 |
--dimAt, --maskDimAt; |
| 212 |
} |
| 213 |
accumulator.Done(elements.back()); |
| 214 |
} |
| 215 |
} else { // no DIM=, result is scalar |
| 216 |
elements.push_back(identity); |
| 217 |
bool firstUnmasked{true}; |
| 218 |
for (auto n{array.size()}; n-- > 0; |
| 219 |
array.IncrementSubscripts(at), mask.IncrementSubscripts(maskAt)) { |
| 220 |
if (mask.At(maskAt).IsTrue()) { |
| 221 |
accumulator(elements.back(), at, firstUnmasked); |
| 222 |
firstUnmasked = false; |
| 223 |
} |
| 224 |
} |
| 225 |
accumulator.Done(elements.back()); |
| 226 |
} |
| 227 |
if constexpr (T::category == TypeCategory::Character) { |
| 228 |
return {static_cast<ConstantSubscript>(identity.size()), |
| 229 |
std::move(elements), std::move(resultShape)}; |
| 230 |
} else { |
| 231 |
return {std::move(elements), std::move(resultShape)}; |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
// MAXVAL & MINVAL |
| 236 |
template <typename T, bool ABS = false> class MaxvalMinvalAccumulator { |
| 237 |
public: |
| 238 |
MaxvalMinvalAccumulator( |
| 239 |
RelationalOperator opr, FoldingContext &context, const Constant<T> &array) |
| 240 |
: opr_{opr}, context_{context}, array_{array} {}; |
| 241 |
void operator()(Scalar<T> &element, const ConstantSubscripts &at, |
| 242 |
[[maybe_unused]] bool firstUnmasked) const { |
| 243 |
auto aAt{array_.At(at)}; |
| 244 |
if constexpr (ABS) { |
| 245 |
aAt = aAt.ABS(); |
| 246 |
} |
| 247 |
if constexpr (T::category == TypeCategory::Real) { |
| 248 |
if (firstUnmasked || element.IsNotANumber()) { |
| 249 |
// Return NaN if and only if all unmasked elements are NaNs and |
| 250 |
// at least one unmasked element is visible. |
| 251 |
element = aAt; |
| 252 |
return; |
| 253 |
} |
| 254 |
} |
| 255 |
Expr<LogicalResult> test{PackageRelation( |
| 256 |
opr_, Expr<T>{Constant<T>{aAt}}, Expr<T>{Constant<T>{element}})}; |
| 257 |
auto folded{GetScalarConstantValue<LogicalResult>( |
| 258 |
test.Rewrite(context_, std::move(test)))}; |
| 259 |
CHECK(folded.has_value()); |
| 260 |
if (folded->IsTrue()) { |
| 261 |
element = aAt; |
| 262 |
} |
| 263 |
} |
| 264 |
void Done(Scalar<T> &) const {} |
| 265 |
|
| 266 |
private: |
| 267 |
RelationalOperator opr_; |
| 268 |
FoldingContext &context_; |
| 269 |
const Constant<T> &array_; |
| 270 |
}; |
| 271 |
|
| 272 |
template <typename T> |
| 273 |
static Expr<T> FoldMaxvalMinval(FoldingContext &context, FunctionRef<T> &&ref, |
| 274 |
RelationalOperator opr, const Scalar<T> &identity) { |
| 275 |
static_assert(T::category == TypeCategory::Integer || |
| 276 |
T::category == TypeCategory::Real || |
| 277 |
T::category == TypeCategory::Character); |
| 278 |
std::optional<int> dim; |
| 279 |
if (std::optional<ArrayAndMask<T>> arrayAndMask{ |
| 280 |
ProcessReductionArgs<T>(context, ref.arguments(), dim, |
| 281 |
/*ARRAY=*/0, /*DIM=*/1, /*MASK=*/2)}) { |
| 282 |
MaxvalMinvalAccumulator accumulator{opr, context, arrayAndMask->array}; |
| 283 |
return Expr<T>{DoReduction<T>( |
| 284 |
arrayAndMask->array, arrayAndMask->mask, dim, identity, accumulator)}; |
| 285 |
} |
| 286 |
return Expr<T>{std::move(ref)}; |
| 287 |
} |
| 288 |
|
| 289 |
// PRODUCT |
| 290 |
template <typename T> class ProductAccumulator { |
| 291 |
public: |
| 292 |
ProductAccumulator(const Constant<T> &array) : array_{array} {} |
| 293 |
void operator()( |
| 294 |
Scalar<T> &element, const ConstantSubscripts &at, bool /*first*/) { |
| 295 |
if constexpr (T::category == TypeCategory::Integer) { |
| 296 |
auto prod{element.MultiplySigned(array_.At(at))}; |
| 297 |
overflow_ |= prod.SignedMultiplicationOverflowed(); |
| 298 |
element = prod.lower; |
| 299 |
} else { // Real & Complex |
| 300 |
auto prod{element.Multiply(array_.At(at))}; |
| 301 |
overflow_ |= prod.flags.test(RealFlag::Overflow); |
| 302 |
element = prod.value; |
| 303 |
} |
| 304 |
} |
| 305 |
bool overflow() const { return overflow_; } |
| 306 |
void Done(Scalar<T> &) const {} |
| 307 |
|
| 308 |
private: |
| 309 |
const Constant<T> &array_; |
| 310 |
bool overflow_{false}; |
| 311 |
}; |
| 312 |
|
| 313 |
template <typename T> |
| 314 |
static Expr<T> FoldProduct( |
| 315 |
FoldingContext &context, FunctionRef<T> &&ref, Scalar<T> identity) { |
| 316 |
static_assert(T::category == TypeCategory::Integer || |
| 317 |
T::category == TypeCategory::Real || |
| 318 |
T::category == TypeCategory::Complex); |
| 319 |
std::optional<int> dim; |
| 320 |
if (std::optional<ArrayAndMask<T>> arrayAndMask{ |
| 321 |
ProcessReductionArgs<T>(context, ref.arguments(), dim, |
| 322 |
/*ARRAY=*/0, /*DIM=*/1, /*MASK=*/2)}) { |
| 323 |
ProductAccumulator accumulator{arrayAndMask->array}; |
| 324 |
auto result{Expr<T>{DoReduction<T>( |
| 325 |
arrayAndMask->array, arrayAndMask->mask, dim, identity, accumulator)}}; |
| 326 |
if (accumulator.overflow() && |
| 327 |
context.languageFeatures().ShouldWarn( |
| 328 |
common::UsageWarning::FoldingException)) { |
| 329 |
context.messages().Say( |
| 330 |
"PRODUCT() of %s data overflowed"_warn_en_US, T::AsFortran()); |
| 331 |
} |
| 332 |
return result; |
| 333 |
} |
| 334 |
return Expr<T>{std::move(ref)}; |
| 335 |
} |
| 336 |
|
| 337 |
// SUM |
| 338 |
template <typename T> class SumAccumulator { |
| 339 |
using Element = typename Constant<T>::Element; |
| 340 |
|
| 341 |
public: |
| 342 |
SumAccumulator(const Constant<T> &array, Rounding rounding) |
| 343 |
: array_{array}, rounding_{rounding} {} |
| 344 |
void operator()( |
| 345 |
Element &element, const ConstantSubscripts &at, bool /*first*/) { |
| 346 |
if constexpr (T::category == TypeCategory::Integer) { |
| 347 |
auto sum{element.AddSigned(array_.At(at))}; |
| 348 |
overflow_ |= sum.overflow; |
| 349 |
element = sum.value; |
| 350 |
} else { // Real & Complex: use Kahan summation |
| 351 |
auto next{array_.At(at).Add(correction_, rounding_)}; |
| 352 |
overflow_ |= next.flags.test(RealFlag::Overflow); |
| 353 |
auto sum{element.Add(next.value, rounding_)}; |
| 354 |
overflow_ |= sum.flags.test(RealFlag::Overflow); |
| 355 |
// correction = (sum - element) - next; algebraically zero |
| 356 |
correction_ = sum.value.Subtract(element, rounding_) |
| 357 |
.value.Subtract(next.value, rounding_) |
| 358 |
.value; |
| 359 |
element = sum.value; |
| 360 |
} |
| 361 |
} |
| 362 |
bool overflow() const { return overflow_; } |
| 363 |
void Done([[maybe_unused]] Element &element) { |
| 364 |
if constexpr (T::category != TypeCategory::Integer) { |
| 365 |
auto corrected{element.Add(correction_, rounding_)}; |
| 366 |
overflow_ |= corrected.flags.test(RealFlag::Overflow); |
| 367 |
correction_ = Scalar<T>{}; |
| 368 |
element = corrected.value; |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
private: |
| 373 |
const Constant<T> &array_; |
| 374 |
Rounding rounding_; |
| 375 |
bool overflow_{false}; |
| 376 |
Element correction_{}; |
| 377 |
}; |
| 378 |
|
| 379 |
template <typename T> |
| 380 |
static Expr<T> FoldSum(FoldingContext &context, FunctionRef<T> &&ref) { |
| 381 |
static_assert(T::category == TypeCategory::Integer || |
| 382 |
T::category == TypeCategory::Real || |
| 383 |
T::category == TypeCategory::Complex); |
| 384 |
using Element = typename Constant<T>::Element; |
| 385 |
std::optional<int> dim; |
| 386 |
Element identity{}; |
| 387 |
if (std::optional<ArrayAndMask<T>> arrayAndMask{ |
| 388 |
ProcessReductionArgs<T>(context, ref.arguments(), dim, |
| 389 |
/*ARRAY=*/0, /*DIM=*/1, /*MASK=*/2)}) { |
| 390 |
SumAccumulator accumulator{ |
| 391 |
arrayAndMask->array, context.targetCharacteristics().roundingMode()}; |
| 392 |
auto result{Expr<T>{DoReduction<T>( |
| 393 |
arrayAndMask->array, arrayAndMask->mask, dim, identity, accumulator)}}; |
| 394 |
if (accumulator.overflow() && |
| 395 |
context.languageFeatures().ShouldWarn( |
| 396 |
common::UsageWarning::FoldingException)) { |
| 397 |
context.messages().Say( |
| 398 |
"SUM() of %s data overflowed"_warn_en_US, T::AsFortran()); |
| 399 |
} |
| 400 |
return result; |
| 401 |
} |
| 402 |
return Expr<T>{std::move(ref)}; |
| 403 |
} |
| 404 |
|
| 405 |
// Utility for IALL, IANY, IPARITY, ALL, ANY, & PARITY |
| 406 |
template <typename T> class OperationAccumulator { |
| 407 |
public: |
| 408 |
OperationAccumulator(const Constant<T> &array, |
| 409 |
Scalar<T> (Scalar<T>::*operation)(const Scalar<T> &) const) |
| 410 |
: array_{array}, operation_{operation} {} |
| 411 |
void operator()( |
| 412 |
Scalar<T> &element, const ConstantSubscripts &at, bool /*first*/) { |
| 413 |
element = (element.*operation_)(array_.At(at)); |
| 414 |
} |
| 415 |
void Done(Scalar<T> &) const {} |
| 416 |
|
| 417 |
private: |
| 418 |
const Constant<T> &array_; |
| 419 |
Scalar<T> (Scalar<T>::*operation_)(const Scalar<T> &) const; |
| 420 |
}; |
| 421 |
|
| 422 |
} // namespace Fortran::evaluate |
| 423 |
#endif // FORTRAN_EVALUATE_FOLD_REDUCTION_H_ |