9#ifndef FORTRAN_EVALUATE_FOLD_MATMUL_H_
10#define FORTRAN_EVALUATE_FOLD_MATMUL_H_
12#include "fold-implementation.h"
18 const int kind{funcRef.kind()};
19 using Element =
typename Constant<T>::Element;
20 auto args{funcRef.arguments()};
21 CHECK(args.size() == 2);
26 return Expr<T>{std::move(funcRef)};
28 CHECK(ma->Rank() >= 1 && ma->Rank() <= 2 && mb->Rank() >= 1 &&
29 mb->Rank() <= 2 && (ma->Rank() == 2 || mb->Rank() == 2));
30 ConstantSubscript commonExtent{ma->shape().back()};
31 if (mb->shape().front() != commonExtent) {
32 context.messages().Say(
33 "Arguments to MATMUL have distinct extents %zd and %zd on their last and first dimensions"_err_en_US,
34 commonExtent, mb->shape().front());
35 return MakeInvalidIntrinsic(std::move(funcRef));
37 ConstantSubscript rows{ma->Rank() == 1 ? 1 : ma->shape()[0]};
38 ConstantSubscript columns{mb->Rank() == 1 ? 1 : mb->shape()[1]};
39 std::vector<Element> elements;
40 elements.reserve(rows * columns);
42 [[maybe_unused]]
const auto &rounding{
43 context.targetCharacteristics().roundingMode()};
45 for (ConstantSubscript ci{0}; ci < columns; ++ci) {
46 for (ConstantSubscript ri{0}; ri < rows; ++ri) {
47 ConstantSubscripts aAt{ma->lbounds()};
48 if (ma->Rank() == 2) {
51 ConstantSubscripts bAt{mb->lbounds()};
52 if (mb->Rank() == 2) {
55 Element sum{Element::Zero(kind)};
56 [[maybe_unused]] Element correction{Element::Zero(kind)};
57 for (ConstantSubscript j{0}; j < commonExtent; ++j) {
58 Element aElt{ma->At(aAt)};
59 Element bElt{mb->At(bAt)};
60 if constexpr (T::category == TypeCategory::Real ||
61 T::category == TypeCategory::Complex) {
62 auto product{aElt.Multiply(bElt)};
63 overflow |= product.flags.test(RealFlag::Overflow);
64 if constexpr (useKahanSummation) {
65 auto added{sum.KahanSummation(product.value, correction)};
66 overflow |= added.flags.test(RealFlag::Overflow);
69 auto added{sum.Add(product.value)};
70 overflow |= added.flags.test(RealFlag::Overflow);
73 }
else if constexpr (T::category == TypeCategory::Integer) {
74 auto product{aElt.MultiplySigned(bElt)};
75 overflow |= product.SignedMultiplicationOverflowed();
76 auto added{sum.AddSigned(product.lower)};
77 overflow |= added.overflow;
78 sum = std::move(added.value);
79 }
else if constexpr (T::category == TypeCategory::Unsigned) {
80 sum = sum.AddUnsigned(aElt.MultiplyUnsigned(bElt).lower).value;
82 static_assert(T::category == TypeCategory::Logical);
83 sum = sum.OR(aElt.AND(bElt));
88 elements.push_back(sum);
92 context.Warn(common::UsageWarning::FoldingException,
93 "MATMUL of %s data overflowed during computation"_warn_en_US,
96 ConstantSubscripts shape;
97 if (ma->Rank() == 2) {
98 shape.push_back(rows);
100 if (mb->Rank() == 2) {
101 shape.push_back(columns);
Definition constant.h:181
Definition fold-implementation.h:54