Core: Evaluate lazy products in the storage order their expression reports

libeigen/eigen!3442

Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/Eigen/src/Core/AssignEvaluator.h b/Eigen/src/Core/AssignEvaluator.h
index 9120f95..2728899 100644
--- a/Eigen/src/Core/AssignEvaluator.h
+++ b/Eigen/src/Core/AssignEvaluator.h
@@ -943,11 +943,19 @@
   }
 }
 
+// The evaluator a dense assignment reads its source through. The assignment loops index the source by the
+// destination's storage order and use only the source evaluator's flags, so a source may be evaluated in another
+// storage order than its expression reports; see the coefficient-based product in ProductEvaluators.h.
+template <typename DstEvaluatorType, typename SrcXprType, typename Enable = void>
+struct dense_assignment_source_evaluator {
+  using type = evaluator<SrcXprType>;
+};
+
 template <typename DstXprType, typename SrcXprType, typename Functor>
 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE constexpr void call_dense_assignment_loop(DstXprType& dst, const SrcXprType& src,
                                                                                 const Functor& func) {
   using DstEvaluatorType = evaluator<DstXprType>;
-  using SrcEvaluatorType = evaluator<SrcXprType>;
+  using SrcEvaluatorType = typename dense_assignment_source_evaluator<DstEvaluatorType, SrcXprType>::type;
 
   SrcEvaluatorType srcEvaluator(src);
 
@@ -1057,7 +1065,7 @@
 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void call_restricted_packet_assignment_no_alias(Dst& dst, const Src& src,
                                                                                       const Func& func) {
   using DstEvaluatorType = evaluator<Dst>;
-  using SrcEvaluatorType = evaluator<Src>;
+  using SrcEvaluatorType = typename dense_assignment_source_evaluator<DstEvaluatorType, Src>::type;
   using Kernel = restricted_packet_dense_assignment_kernel<DstEvaluatorType, SrcEvaluatorType, Func>;
 
   EIGEN_STATIC_ASSERT_LVALUE(Dst)
diff --git a/Eigen/src/Core/Product.h b/Eigen/src/Core/Product.h
index 68ca72c..caa1f24 100644
--- a/Eigen/src/Core/Product.h
+++ b/Eigen/src/Core/Product.h
@@ -46,11 +46,19 @@
     // FIXME: only needed by GeneralMatrixMatrixTriangular
     InnerSize = min_size_prefer_fixed(LhsTraits::ColsAtCompileTime, RhsTraits::RowsAtCompileTime),
 
-    // The storage order is somewhat arbitrary here. The correct one will be determined through the evaluator.
+    // Products served by the coefficient-based evaluator are evaluated in the storage order reported below, which
+    // Reverse, Redux, Block, FindCoeff and others use to index their packets and coefficients. Row-major * row-major
+    // is row-major there, so that the rhs rows can be vectorized. A dense product of inner size 1 is served by it in
+    // LazyCoeffBasedProductMode, and materialized otherwise; unlike product_type, this test agrees between host and
+    // device code.
+    CoeffBasedEval = Option == LazyProduct || (std::is_same<StorageKind, Dense>::value && InnerSize == 1),
+
+    // For other products the storage order is somewhat arbitrary: their evaluators materialize a PlainObject of it.
     Flags = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1)   ? RowMajorBit
             : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0
             : (((LhsTraits::Flags & NoPreferredStorageOrderBit) && (RhsTraits::Flags & RowMajorBit)) ||
-               ((RhsTraits::Flags & NoPreferredStorageOrderBit) && (LhsTraits::Flags & RowMajorBit)))
+               ((RhsTraits::Flags & NoPreferredStorageOrderBit) && (LhsTraits::Flags & RowMajorBit)) ||
+               (CoeffBasedEval && (LhsTraits::Flags & RowMajorBit) && (RhsTraits::Flags & RowMajorBit)))
                 ? RowMajorBit
                 : NoPreferredStorageOrderBit
   };
diff --git a/Eigen/src/Core/ProductEvaluators.h b/Eigen/src/Core/ProductEvaluators.h
index bd898a2..72a037a 100644
--- a/Eigen/src/Core/ProductEvaluators.h
+++ b/Eigen/src/Core/ProductEvaluators.h
@@ -590,16 +590,15 @@
   static constexpr bool DstRowMajor = bool(Dst::IsRowMajor);
   static constexpr bool DstContiguous =
       (int(DstEval::Flags) & DirectAccessBit) != 0 && int(Dst::InnerStrideAtCompileTime) == 1;
-  // Orientation of the packets the product evaluator natively produces. When a
-  // product can vectorize *both* the lhs (columns) and the rhs (rows), its
-  // packet() returns column packets (EvalToRowMajor == 0). The cascade axis must
-  // match this orientation -- and the destination's storage order must match it
-  // too, so the contiguous packet store lands on contiguous coefficients.
+  // The product's packets run along its storage order. The cascade axis must match
+  // it -- and so must the destination's storage order, so the contiguous packet
+  // store lands on contiguous coefficients. ProdEval::Vectorize is false for
+  // mixed-scalar products, which keep the generic (scalar) path.
   static constexpr bool ProdRowMajor = (int(ProdEval::Flags) & RowMajorBit) != 0;
   static constexpr bool VecLhs =  // column-major product & dst: vectorize down each column
-      bool(ProdEval::CanVectorizeLhs) && !ProdRowMajor && !DstRowMajor && Rows != Dynamic;
+      bool(ProdEval::Vectorize) && !ProdRowMajor && !DstRowMajor && Rows != Dynamic;
   static constexpr bool VecRhs =  // row-major product & dst: vectorize along each row
-      bool(ProdEval::CanVectorizeRhs) && ProdRowMajor && DstRowMajor && Cols != Dynamic;
+      bool(ProdEval::Vectorize) && ProdRowMajor && DstRowMajor && Cols != Dynamic;
   static constexpr int Extent = VecLhs ? Rows : VecRhs ? Cols : 1;
   using Packet = typename find_largest_packet<Scalar, Extent>::type;
   static constexpr int LargestSize = unpacket_traits<Packet>::size;
@@ -608,12 +607,8 @@
       bool(EIGEN_UNALIGNED_VECTORIZE) &&
       (int(DstEval::Flags) & int(ProdEval::Flags) & int(ActualPacketAccessBit)) != 0 &&
       bool(functor_traits<Func>::PacketAccess);
-  // SameType mirrors the product's own PacketAccessBit (SameType && (CanVectorizeLhs ||
-  // CanVectorizeRhs)): CanVectorizeLhs/Rhs alone test only the operand's packet access, so a
-  // mixed-scalar product (e.g. double * complex) would otherwise enable the cascade and try to
-  // read the wrong-width packet out of an operand. Mixed types keep the generic (scalar) path.
-  static constexpr bool Enable = bool(ProdEval::SameType) && (VecLhs || VecRhs) && DstContiguous && MightVectorize &&
-                                 (LargestSize <= Extent) && (LargestSize > GenericSize);
+  static constexpr bool Enable =
+      (VecLhs || VecRhs) && DstContiguous && MightVectorize && (LargestSize <= Extent) && (LargestSize > GenericSize);
 };
 
 // Run the cascade over every outer index of dst. Traits::VecLhs is a compile-time
@@ -635,10 +630,17 @@
 // a plain `if`) so the cascade is only *instantiated* for the vectorizable
 // fixed-size case -- a runtime branch would instantiate it for every product,
 // including scalar types with no packet support.
+template <typename Lhs, typename Rhs, bool EvalToRowMajor>
+struct coeff_based_product_evaluator;
+
+// The coefficient-based evaluator of lhs * rhs with packets along dst's storage order.
+template <typename Lhs, typename Rhs, typename Dst>
+using dst_ordered_product_evaluator = coeff_based_product_evaluator<Lhs, Rhs, bool(Dst::IsRowMajor)>;
+
 template <typename Func, typename Dst, typename Lhs, typename Rhs>
 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void product_packet_assign(std::true_type, const Func& func, Dst& dst,
                                                                  const Lhs& lhs, const Rhs& rhs) {
-  using ProdEval = product_evaluator<Product<Lhs, Rhs, LazyProduct>, CoeffBasedProductMode, DenseShape, DenseShape>;
+  using ProdEval = dst_ordered_product_evaluator<Lhs, Rhs, Dst>;
   using Traits = product_packet_cascade_traits<ProdEval, Dst, Func>;
   const ProdEval prodEval(lhs, rhs);
   product_run_packet_cascade<Traits>(func, dst, prodEval);
@@ -669,7 +671,7 @@
   template <typename Dst>
   static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) {
     // dst.noalias() += lhs.lazyProduct(rhs);
-    using ProdEval = product_evaluator<Product<Lhs, Rhs, LazyProduct>, CoeffBasedProductMode, DenseShape, DenseShape>;
+    using ProdEval = dst_ordered_product_evaluator<Lhs, Rhs, Dst>;
     using Func = internal::add_assign_op<typename Dst::Scalar, Scalar>;
     using Traits = product_packet_cascade_traits<ProdEval, Dst, Func>;
     product_packet_assign(bool_constant<Traits::Enable>(), Func(), dst, lhs, rhs);
@@ -678,7 +680,7 @@
   template <typename Dst>
   static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) {
     // dst.noalias() -= lhs.lazyProduct(rhs);
-    using ProdEval = product_evaluator<Product<Lhs, Rhs, LazyProduct>, CoeffBasedProductMode, DenseShape, DenseShape>;
+    using ProdEval = dst_ordered_product_evaluator<Lhs, Rhs, Dst>;
     using Func = internal::sub_assign_op<typename Dst::Scalar, Scalar>;
     using Traits = product_packet_cascade_traits<ProdEval, Dst, Func>;
     product_packet_assign(bool_constant<Traits::Enable>(), Func(), dst, lhs, rhs);
@@ -746,19 +748,19 @@
   EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_empty_packet_evaluator(const Xpr&) {}
 };
 
-template <typename Lhs, typename Rhs, int ProductTag>
-struct product_evaluator<Product<Lhs, Rhs, LazyProduct>, ProductTag, DenseShape, DenseShape>
-    : evaluator_base<Product<Lhs, Rhs, LazyProduct>> {
+// Coefficient-based evaluator of lhs * rhs whose packets run along rows if EvalToRowMajor_, else along columns.
+template <typename Lhs, typename Rhs, bool EvalToRowMajor_>
+struct coeff_based_product_evaluator : evaluator_base<Product<Lhs, Rhs, LazyProduct>> {
   using XprType = Product<Lhs, Rhs, LazyProduct>;
   using Scalar = typename XprType::Scalar;
   using CoeffReturnType = typename XprType::CoeffReturnType;
 
-  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr)
-      : product_evaluator(xpr.lhs(), xpr.rhs()) {}
+  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit coeff_based_product_evaluator(const XprType& xpr)
+      : coeff_based_product_evaluator(xpr.lhs(), xpr.rhs()) {}
 
   // Also construct directly from the product operands so packet-cascade callers
   // do not have to materialize a temporary Product expression first.
-  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE product_evaluator(const Lhs& lhs, const Rhs& rhs)
+  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE coeff_based_product_evaluator(const Lhs& lhs, const Rhs& rhs)
       : m_lhs(lhs),
         m_rhs(rhs),
         m_lhsImpl(m_lhs),  // Real evaluator objects for packet products; empty placeholders for scalar-only products.
@@ -826,15 +828,13 @@
   static constexpr bool CanVectorizeRhs = bool(RhsRowMajor) && (RhsFlags & PacketAccessBit) && (ColsAtCompileTime != 1);
   static constexpr bool CanVectorizeLhs = (!LhsRowMajor) && (LhsFlags & PacketAccessBit) && (RowsAtCompileTime != 1);
 
-  static constexpr int EvalToRowMajor = (MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1
-                                        : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1)
-                                            ? 0
-                                            : (bool(RhsRowMajor) && !CanVectorizeLhs);
+  // Only the operand that is contiguous along the packets' axis can vectorize the product.
+  static constexpr bool EvalToRowMajor = EvalToRowMajor_;
+  // TODO: enable vectorization for mixed types
+  static constexpr bool Vectorize = SameType && (EvalToRowMajor ? CanVectorizeRhs : CanVectorizeLhs);
 
   static constexpr int Flags = ((int(LhsFlags) | int(RhsFlags)) & HereditaryBits & ~RowMajorBit) |
-                               (EvalToRowMajor ? RowMajorBit : 0)
-                               // TODO: enable vectorization for mixed types
-                               | (SameType && (CanVectorizeLhs || CanVectorizeRhs) ? PacketAccessBit : 0) |
+                               (EvalToRowMajor ? RowMajorBit : 0) | (Vectorize ? PacketAccessBit : 0) |
                                (XprType::IsVectorAtCompileTime ? LinearAccessBit : 0);
   using LhsPacketEtorType =
       std::conditional_t<bool(int(Flags) & PacketAccessBit), LhsEtorType, product_empty_packet_evaluator>;
@@ -849,15 +849,12 @@
   static constexpr int RhsOuterStrideBytes =
       int(RhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename RhsNestedCleaned::Scalar));
 
+  // Packets come from the operand that vectorizes the product, at its outer index k.
+  static constexpr int VecOuterStrideBytes = EvalToRowMajor ? RhsOuterStrideBytes : LhsOuterStrideBytes;
+  static constexpr int VecAlignment = EvalToRowMajor ? RhsAlignment : LhsAlignment;
   static constexpr int Alignment =
-      bool(CanVectorizeLhs)
-          ? (LhsOuterStrideBytes <= 0 || (int(LhsOuterStrideBytes) % plain_enum_max(1, LhsAlignment)) != 0
-                 ? 0
-                 : LhsAlignment)
-      : bool(CanVectorizeRhs)
-          ? (RhsOuterStrideBytes <= 0 || (int(RhsOuterStrideBytes) % plain_enum_max(1, RhsAlignment)) != 0
-                 ? 0
-                 : RhsAlignment)
+      (Vectorize && VecOuterStrideBytes > 0 && VecOuterStrideBytes % plain_enum_max(1, VecAlignment) == 0)
+          ? VecAlignment
           : 0;
 
   EIGEN_DEVICE_FUNC constexpr EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index row, Index col) const {
@@ -932,12 +929,39 @@
   variable_if_dynamic<Index, InnerSize> m_innerDim;
 };
 
+// Evaluate in the storage order the expression reports, which consumers such as Reverse, Redux, Block and FindCoeff
+// use to index packets and size their loops.
+template <typename Lhs, typename Rhs, int ProductTag>
+struct product_evaluator<Product<Lhs, Rhs, LazyProduct>, ProductTag, DenseShape, DenseShape>
+    : coeff_based_product_evaluator<Lhs, Rhs, (int(traits<Product<Lhs, Rhs, LazyProduct>>::Flags) & RowMajorBit) != 0> {
+  using XprType = Product<Lhs, Rhs, LazyProduct>;
+  using Base =
+      coeff_based_product_evaluator<Lhs, Rhs, (int(traits<Product<Lhs, Rhs, LazyProduct>>::Flags) & RowMajorBit) != 0>;
+
+  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr) : Base(xpr) {}
+  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE product_evaluator(const Lhs& lhs, const Rhs& rhs) : Base(lhs, rhs) {}
+};
+
+// A dense assignment reads its source only through the evaluator, so it may evaluate a coefficient-based product
+// along the destination's storage order, which the destination's packets need. It does so only where that order
+// vectorizes; otherwise the assignment is scalar in either order, and the expression's evaluator is kept.
+template <typename DstEvaluatorType, typename Lhs, typename Rhs>
+struct dense_assignment_source_evaluator<
+    DstEvaluatorType, Product<Lhs, Rhs, LazyProduct>,
+    std::enable_if_t<std::is_same<typename evaluator_traits<Lhs>::Shape, DenseShape>::value &&
+                     std::is_same<typename evaluator_traits<Rhs>::Shape, DenseShape>::value>> {
+  using DstOrdered = coeff_based_product_evaluator<Lhs, Rhs, (int(DstEvaluatorType::Flags) & RowMajorBit) != 0>;
+  using type = std::conditional_t<DstOrdered::Vectorize, DstOrdered, evaluator<Product<Lhs, Rhs, LazyProduct>>>;
+};
+
 template <typename Lhs, typename Rhs>
 struct product_evaluator<Product<Lhs, Rhs, DefaultProduct>, LazyCoeffBasedProductMode, DenseShape, DenseShape>
     : product_evaluator<Product<Lhs, Rhs, LazyProduct>, CoeffBasedProductMode, DenseShape, DenseShape> {
   using XprType = Product<Lhs, Rhs, DefaultProduct>;
   using BaseProduct = Product<Lhs, Rhs, LazyProduct>;
   using Base = product_evaluator<BaseProduct, CoeffBasedProductMode, DenseShape, DenseShape>;
+  static_assert((int(traits<XprType>::Flags) & RowMajorBit) == (int(Base::Flags) & RowMajorBit),
+                "the evaluator must use the storage order its expression reports");
   enum { Flags = Base::Flags | EvalBeforeNestingBit };
   EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr)
       : Base(BaseProduct(xpr.lhs(), xpr.rhs())) {}
diff --git a/benchmarks/Core/CMakeLists.txt b/benchmarks/Core/CMakeLists.txt
index c5e8f58..3410ccb 100644
--- a/benchmarks/Core/CMakeLists.txt
+++ b/benchmarks/Core/CMakeLists.txt
@@ -124,6 +124,7 @@
 eigen_add_benchmark(bench_small_dynamic_product bench_small_dynamic_product.cpp)
 eigen_add_benchmark(bench_scaled_product bench_scaled_product.cpp)
 eigen_add_benchmark(bench_outer_product bench_outer_product.cpp)
+eigen_add_benchmark(bench_product_storage_order bench_product_storage_order.cpp)
 eigen_add_benchmark(bench_selfadjoint_diagonal bench_selfadjoint_diagonal.cpp)
 eigen_add_benchmark(bench_segment_tail bench_segment_tail.cpp)
 eigen_add_benchmark(bench_boolean_ops bench_boolean_ops.cpp)
diff --git a/benchmarks/Core/bench_product_storage_order.cpp b/benchmarks/Core/bench_product_storage_order.cpp
new file mode 100644
index 0000000..e6e92c5
--- /dev/null
+++ b/benchmarks/Core/bench_product_storage_order.cpp
@@ -0,0 +1,107 @@
+// Small fixed-size products for every storage order of the operands and the destination. An assignment evaluates the
+// coefficient-based product along the destination's storage order, which vectorizes when the operand that runs along
+// it is contiguous: the lhs for a column-major destination, the rhs for a row-major one.
+// SPDX-FileCopyrightText: The Eigen Authors
+// SPDX-License-Identifier: MPL-2.0
+
+#include <benchmark/benchmark.h>
+#include <Eigen/Core>
+
+using namespace Eigen;
+
+#ifndef SCALAR
+#define SCALAR float
+#endif
+
+using Scalar = SCALAR;
+using RealScalar = NumTraits<Scalar>::Real;
+
+template <typename Dst, typename Lhs, typename Rhs>
+static bool matches_reference(const Dst& dst, const Dst& before, const Lhs& lhs, const Rhs& rhs) {
+  for (Index i = 0; i < dst.rows(); ++i) {
+    for (Index j = 0; j < dst.cols(); ++j) {
+      Scalar sum = before(i, j);
+      RealScalar scale = numext::abs(before(i, j));
+      for (Index k = 0; k < lhs.cols(); ++k) {
+        sum += lhs(i, k) * rhs(k, j);
+        scale += numext::abs(lhs(i, k)) * numext::abs(rhs(k, j));
+      }
+      if (!(numext::abs(dst(i, j) - sum) <= RealScalar(8) * NumTraits<RealScalar>::epsilon() * scale)) return false;
+    }
+  }
+  return true;
+}
+
+// dst = lhs * rhs (Accumulate == false) or dst += lhs * rhs.
+template <int N, int LhsOrder, int RhsOrder, int DstOrder, bool Accumulate>
+static void BM_ProductOrder(benchmark::State& state) {
+  const Matrix<Scalar, N, N, LhsOrder> lhs = Matrix<Scalar, N, N, LhsOrder>::Random();
+  const Matrix<Scalar, N, N, RhsOrder> rhs = Matrix<Scalar, N, N, RhsOrder>::Random();
+  using Dst = Matrix<Scalar, N, N, DstOrder>;
+  Dst dst = Accumulate ? Dst(Dst::Random()) : Dst(Dst::Zero());
+  const Dst before = dst;
+  if (Accumulate)
+    dst.noalias() += lhs * rhs;
+  else
+    dst.noalias() = lhs * rhs;
+  if (!matches_reference(dst, before, lhs, rhs)) {
+    state.SkipWithError("Product disagrees with the scalar reference");
+    return;
+  }
+  for (auto _ : state) {
+    benchmark::DoNotOptimize(lhs.data());
+    benchmark::DoNotOptimize(rhs.data());
+    if (Accumulate)
+      dst.noalias() += lhs * rhs;
+    else
+      dst.noalias() = lhs * rhs;
+    benchmark::DoNotOptimize(dst.data());
+    benchmark::ClobberMemory();
+  }
+  state.SetItemsProcessed(state.iterations() * N * N * N);
+}
+
+// dst -= src.col(k) * src.row(k): a rank-1 update with a strided column and a contiguous row when Order is RowMajor.
+template <int N, int Order>
+static void BM_RankOneUpdate(benchmark::State& state) {
+  using Mat = Matrix<Scalar, N, N, Order>;
+  const Mat src = Mat::Random();
+  Mat dst = Mat::Random();
+  const Mat before = dst;
+  dst.noalias() -= src.col(1) * src.row(2);
+  if (!matches_reference(dst, before, -src.col(1), src.row(2))) {
+    state.SkipWithError("Rank-1 update disagrees with the scalar reference");
+    return;
+  }
+  for (auto _ : state) {
+    benchmark::DoNotOptimize(src.data());
+    dst.noalias() -= src.col(1) * src.row(2);
+    benchmark::DoNotOptimize(dst.data());
+    benchmark::ClobberMemory();
+  }
+  state.SetItemsProcessed(state.iterations() * N * N);
+}
+
+#define PRODUCT_ORDERS(N, ACC)                                               \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, ColMajor, ColMajor, ColMajor, ACC); \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, ColMajor, ColMajor, RowMajor, ACC); \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, ColMajor, RowMajor, ColMajor, ACC); \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, ColMajor, RowMajor, RowMajor, ACC); \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, RowMajor, ColMajor, ColMajor, ACC); \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, RowMajor, ColMajor, RowMajor, ACC); \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, RowMajor, RowMajor, ColMajor, ACC); \
+  BENCHMARK_TEMPLATE(BM_ProductOrder, N, RowMajor, RowMajor, RowMajor, ACC)
+
+PRODUCT_ORDERS(3, false);
+PRODUCT_ORDERS(4, false);
+PRODUCT_ORDERS(8, false);
+PRODUCT_ORDERS(3, true);
+PRODUCT_ORDERS(4, true);
+PRODUCT_ORDERS(8, true);
+
+BENCHMARK_TEMPLATE(BM_RankOneUpdate, 4, ColMajor);
+BENCHMARK_TEMPLATE(BM_RankOneUpdate, 4, RowMajor);
+BENCHMARK_TEMPLATE(BM_RankOneUpdate, 8, ColMajor);
+BENCHMARK_TEMPLATE(BM_RankOneUpdate, 8, RowMajor);
+BENCHMARK_TEMPLATE(BM_RankOneUpdate, 16, ColMajor);
+BENCHMARK_TEMPLATE(BM_RankOneUpdate, 16, RowMajor);
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 11374cf..616bc7e 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -412,6 +412,7 @@
 endif()
 ei_add_test(product_extra)
 ei_add_test(product_evaluators)
+ei_add_test(product_storage_order)
 ei_add_test(diagonalmatrices)
 ei_add_test(diagonalview)
 ei_add_test(skew_symmetric_matrix3)
diff --git a/test/product_storage_order.cpp b/test/product_storage_order.cpp
new file mode 100644
index 0000000..4a09e00
--- /dev/null
+++ b/test/product_storage_order.cpp
@@ -0,0 +1,137 @@
+// This file is part of Eigen, a lightweight C++ template library
+// for linear algebra.
+//
+// This Source Code Form is subject to the terms of the Mozilla
+// Public License v. 2.0. If a copy of the MPL was not distributed
+// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
+// SPDX-FileCopyrightText: The Eigen Authors
+// SPDX-License-Identifier: MPL-2.0
+
+// A product served by the coefficient-based evaluator must be evaluated in the storage order its expression reports:
+// Reverse, Redux, PartialRedux, Block, Replicate and FindCoeff index its packets and coefficients by that order, or
+// size their loops by it. Each consumer is checked against the materialized product.
+
+#include "main.h"
+
+// Integer entries stay small so that the products cannot overflow.
+template <typename MatrixType>
+MatrixType random_operand() {
+  using Scalar = typename MatrixType::Scalar;
+  return MatrixType::NullaryExpr([] {
+    return NumTraits<Scalar>::IsInteger ? internal::random<Scalar>(Scalar(-8), Scalar(8)) : internal::random<Scalar>();
+  });
+}
+
+template <typename Prod>
+void check_min_max(const Prod&, const Matrix<typename Prod::Scalar, Dynamic, Dynamic>&, std::true_type) {}
+
+template <typename Prod>
+void check_min_max(const Prod& prod, const Matrix<typename Prod::Scalar, Dynamic, Dynamic>& ref, std::false_type) {
+  VERIFY_IS_APPROX(prod.minCoeff(), ref.minCoeff());
+  Index i = -1, j = -1;
+  const typename Prod::Scalar m = prod.maxCoeff(&i, &j);
+  VERIFY(i >= 0 && i < ref.rows() && j >= 0 && j < ref.cols());
+  VERIFY_IS_APPROX(m, ref(i, j));
+  VERIFY_IS_APPROX(m, ref.maxCoeff());
+}
+
+template <typename Prod>
+void check_consumers(const Prod& prod) {
+  using Scalar = typename Prod::Scalar;
+  using RealScalar = typename NumTraits<Scalar>::Real;
+  using Plain = Matrix<Scalar, Dynamic, Dynamic>;
+  const Plain& lhs = prod.lhs();
+  const Plain& rhs = prod.rhs();
+  const Plain ref = lhs * rhs;
+
+  VERIFY_IS_EQUAL(bool(Prod::IsRowMajor), bool(int(internal::evaluator<Prod>::Flags) & RowMajorBit));
+  VERIFY_IS_APPROX(Plain(prod), ref);
+  VERIFY_IS_APPROX(Plain(prod.reverse()), Plain(ref.reverse()));
+  VERIFY_IS_APPROX(Plain(prod.colwise().reverse()), Plain(ref.colwise().reverse()));
+  VERIFY_IS_APPROX(Plain(prod.rowwise().reverse()), Plain(ref.rowwise().reverse()));
+  VERIFY_IS_APPROX(Plain(prod.colwise().sum()), Plain(ref.colwise().sum()));
+  VERIFY_IS_APPROX(Plain(prod.rowwise().sum()), Plain(ref.rowwise().sum()));
+  double magnitude = 0;
+  for (Index j = 0; j < rhs.cols(); ++j)
+    for (Index i = 0; i < lhs.rows(); ++i)
+      for (Index k = 0; k < lhs.cols(); ++k)
+        magnitude += static_cast<double>(numext::abs(lhs(i, k))) * static_cast<double>(numext::abs(rhs(k, j)));
+  // Two k-term products and mn-term reductions; the factor 4 also covers complex arithmetic.
+  const double sum_bound =
+      4 * (double(lhs.cols()) + double(ref.size())) * double(NumTraits<RealScalar>::epsilon()) * magnitude;
+  VERIFY((numext::isfinite)(sum_bound));
+  VERIFY(static_cast<double>(numext::abs(prod.sum() - ref.sum())) <= sum_bound);
+  VERIFY_IS_APPROX(prod.squaredNorm(), ref.squaredNorm());
+  VERIFY_IS_APPROX(prod.cwiseAbs().sum(), ref.cwiseAbs().sum());
+  check_min_max(prod, ref, internal::bool_constant<NumTraits<Scalar>::IsComplex>());
+  const Matrix<Scalar, Dynamic, Dynamic, ColMajor> col_major = prod.block(0, 0, ref.rows(), ref.cols());
+  const Matrix<Scalar, Dynamic, Dynamic, RowMajor> row_major = prod.block(0, 0, ref.rows(), ref.cols());
+  VERIFY_IS_APPROX(Plain(col_major), ref);
+  VERIFY_IS_APPROX(Plain(row_major), ref);
+  VERIFY_IS_APPROX(Plain(prod.replicate(2, 3)), Plain(ref.replicate(2, 3)));
+}
+
+template <typename Scalar, int Rows, int Cols, int Order>
+using MatrixOf = typename internal::make_proper_matrix_type<Scalar, Rows, Cols, Order>::type;
+
+template <typename Scalar, int M, int K, int N>
+void lazy_products() {
+  const MatrixOf<Scalar, M, K, RowMajor> lr = random_operand<MatrixOf<Scalar, M, K, RowMajor>>();
+  const MatrixOf<Scalar, M, K, ColMajor> lc = random_operand<MatrixOf<Scalar, M, K, ColMajor>>();
+  const MatrixOf<Scalar, K, N, RowMajor> rr = random_operand<MatrixOf<Scalar, K, N, RowMajor>>();
+  const MatrixOf<Scalar, K, N, ColMajor> rc = random_operand<MatrixOf<Scalar, K, N, ColMajor>>();
+  check_consumers(lr.lazyProduct(rr));
+  check_consumers(lc.lazyProduct(rr));
+  check_consumers(lr.lazyProduct(rc));
+  check_consumers(lc.lazyProduct(rc));
+  // A nested product has no preferred storage order.
+  const Matrix<Scalar, K, K> identity = Matrix<Scalar, K, K>::Identity();
+  check_consumers((lc * identity).lazyProduct(rr));
+  check_consumers(lr.lazyProduct(identity * rc));
+  // Expression operands.
+  const MatrixOf<Scalar, K, M, ColMajor> lct = random_operand<MatrixOf<Scalar, K, M, ColMajor>>();
+  const Matrix<Scalar, M + 2, K + 2, RowMajor> big = random_operand<Matrix<Scalar, M + 2, K + 2, RowMajor>>();
+  check_consumers(lct.transpose().lazyProduct(rr));
+  check_consumers((Scalar(2) * lr).lazyProduct(rr));
+  check_consumers(lr.conjugate().lazyProduct(rr));
+  check_consumers(big.template block<M, K>(1, 1).lazyProduct(rr));
+
+  const Matrix<Scalar, Dynamic, Dynamic, RowMajor> dlr = lr, drr = rr;
+  const Matrix<Scalar, Dynamic, Dynamic, ColMajor> dlc = lc, drc = rc;
+  check_consumers(dlr.lazyProduct(drr));
+  check_consumers(dlc.lazyProduct(drr));
+  check_consumers(dlr.lazyProduct(drc));
+}
+
+// Default products with a unit inner dimension are served by the coefficient-based evaluator without being
+// materialized.
+template <typename Scalar>
+void outer_products() {
+  const Matrix<Scalar, 8, 8, RowMajor> a = random_operand<Matrix<Scalar, 8, 8, RowMajor>>();
+  const Matrix<Scalar, 8, 8, ColMajor> b = random_operand<Matrix<Scalar, 8, 8, ColMajor>>();
+  const Matrix<Scalar, 1, 7> v = random_operand<Matrix<Scalar, 1, 7>>();
+  check_consumers(a.col(2) * v);
+  check_consumers(b.col(2) * v);
+  check_consumers(a.col(2) * a.row(3).template head<7>());
+  // Depth 1 from the rhs alone: the lhs has a runtime number of columns.
+  const Matrix<Scalar, Dynamic, Dynamic, RowMajor> d = a.col(5);
+  check_consumers(d * v);
+}
+
+EIGEN_DECLARE_TEST(product_storage_order) {
+  for (int i = 0; i < g_repeat; ++i) {
+    CALL_SUBTEST_1((lazy_products<float, 3, 3, 5>()));
+    CALL_SUBTEST_1((lazy_products<float, 8, 4, 5>()));
+    CALL_SUBTEST_1((lazy_products<float, 16, 2, 17>()));
+    CALL_SUBTEST_1(outer_products<float>());
+    CALL_SUBTEST_2((lazy_products<double, 6, 2, 7>()));
+    CALL_SUBTEST_2((lazy_products<double, 4, 1, 9>()));
+    CALL_SUBTEST_2((lazy_products<double, 1, 3, 8>()));
+    CALL_SUBTEST_2(outer_products<double>());
+    CALL_SUBTEST_3((lazy_products<std::complex<float>, 5, 3, 6>()));
+    CALL_SUBTEST_3(outer_products<std::complex<float>>());
+    CALL_SUBTEST_4((lazy_products<std::complex<double>, 4, 2, 5>()));
+    CALL_SUBTEST_5((lazy_products<int, 8, 3, 8>()));
+    CALL_SUBTEST_5(outer_products<int>());
+  }
+}
diff --git a/test/vectorization_logic.cpp b/test/vectorization_logic.cpp
index 9af8145..77f3352 100644
--- a/test/vectorization_logic.cpp
+++ b/test/vectorization_logic.cpp
@@ -35,12 +35,16 @@
 using internal::demangle_traversal;
 using internal::demangle_unrolling;
 
+// The traits of the kernel that `Dst = Src` runs, with the source evaluator the assignment uses.
+template <typename Dst, typename Src>
+using assign_traits = internal::copy_using_evaluator_traits<
+    internal::evaluator<Dst>, typename internal::dense_assignment_source_evaluator<internal::evaluator<Dst>, Src>::type,
+    internal::assign_op<typename Dst::Scalar, typename Src::Scalar>>;
+
 template <typename Dst, typename Src>
 bool test_assign(const Dst&, const Src&, int traversal, int unrolling) {
   EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Dst, Src);
-  typedef internal::copy_using_evaluator_traits<internal::evaluator<Dst>, internal::evaluator<Src>,
-                                                internal::assign_op<typename Dst::Scalar, typename Src::Scalar> >
-      traits;
+  using traits = assign_traits<Dst, Src>;
   // If traversal or unrolling are negative, ignore.
   bool res = traversal > -1 ? traits::Traversal == traversal : true;
   if (unrolling > -1) {
@@ -67,9 +71,7 @@
 template <typename Dst, typename Src>
 bool test_assign(int traversal, int unrolling) {
   EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Dst, Src);
-  typedef internal::copy_using_evaluator_traits<internal::evaluator<Dst>, internal::evaluator<Src>,
-                                                internal::assign_op<typename Dst::Scalar, typename Src::Scalar> >
-      traits;
+  using traits = assign_traits<Dst, Src>;
   bool res = traits::Traversal == traversal && traits::Unrolling == unrolling;
   if (!res) {
     std::cerr << "Src: " << demangle_flags(Src::Flags) << std::endl;
@@ -222,6 +224,17 @@
                          int(Matrix11::SizeAtCompileTime) * CostP11 <= BudgetP11        ? CompleteUnrolling
                          : int(Matrix11::InnerSizeAtCompileTime) * CostP11 <= BudgetP11 ? InnerUnrolling
                                                                                         : NoUnrolling));
+
+      // An assignment evaluates a lazy product along the destination's storage order, so it vectorizes whenever the
+      // operand along that order is contiguous, whatever order the product expression reports.
+      using MatrixC = Matrix<Scalar, PacketSize, PacketSize, ColMajor>;
+      using MatrixR = Matrix<Scalar, PacketSize, PacketSize, RowMajor>;
+      VERIFY(test_assign(MatrixC(), MatrixC().lazyProduct(MatrixC()), InnerVectorizedTraversal, -1));
+      VERIFY(test_assign(MatrixC(), MatrixC().lazyProduct(MatrixR()), InnerVectorizedTraversal, -1));
+      VERIFY(test_assign(MatrixR(), MatrixC().lazyProduct(MatrixR()), InnerVectorizedTraversal, -1));
+      VERIFY(test_assign(MatrixR(), MatrixR().lazyProduct(MatrixR()), InnerVectorizedTraversal, -1));
+      // The strided column cannot vectorize the product, the contiguous row can.
+      VERIFY(test_assign(MatrixR(), MatrixR().col(0).lazyProduct(MatrixR().row(0)), InnerVectorizedTraversal, -1));
     }
 
     VERIFY(test_redux(Vector1(), LinearVectorizedTraversal, CompleteUnrolling));