Core: Fix and tighten dense Block accessors and evaluator flags

libeigen/eigen!3431

Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/Eigen/src/Core/Block.h b/Eigen/src/Core/Block.h
index c995430..6c337e3 100644
--- a/Eigen/src/Core/Block.h
+++ b/Eigen/src/Core/Block.h
@@ -187,11 +187,22 @@
 
 namespace internal {
 
-/** \internal Internal implementation of dense Blocks in the general case. */
+/** \internal Start of the row or column taken by the Block(xpr, i) constructor: a row if and only if BlockRows == 1
+ * and BlockCols == XprType::ColsAtCompileTime, a column if and only if BlockRows == XprType::RowsAtCompileTime and
+ * BlockCols == 1. A 1x1 xpr is both, with i == 0. */
+template <typename XprType, int BlockRows, int BlockCols>
+struct block_vector_start {
+  static constexpr Index row(Index i) { return (BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) ? i : 0; }
+  static constexpr Index col(Index i) { return (BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) ? i : 0; }
+};
+
+/** \internal Internal implementation of dense Blocks in the general case. Coefficient and packet access go through
+ * DenseCoeffsBase and evaluator<Block>. */
 template <typename XprType, int BlockRows, int BlockCols, bool InnerPanel, bool HasDirectAccess>
 class BlockImpl_dense : public internal::dense_xpr_base<Block<XprType, BlockRows, BlockCols, InnerPanel>>::type {
   using BlockType = Block<XprType, BlockRows, BlockCols, InnerPanel>;
   using XprTypeNested = typename internal::ref_selector<XprType>::non_const_type;
+  using VectorStart = block_vector_start<XprType, BlockRows, BlockCols>;
 
  public:
   using Base = typename internal::dense_xpr_base<BlockType>::type;
@@ -202,12 +213,8 @@
    */
   EIGEN_DEVICE_FUNC constexpr BlockImpl_dense(XprType& xpr, Index i)
       : m_xpr(xpr),
-        // It is a row if and only if BlockRows==1 and BlockCols==XprType::ColsAtCompileTime,
-        // and it is a column if and only if BlockRows==XprType::RowsAtCompileTime and BlockCols==1,
-        // all other cases are invalid.
-        // The case a 1x1 matrix seems ambiguous, but the result is the same anyway.
-        m_startRow((BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) ? i : 0),
-        m_startCol((BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) ? i : 0),
+        m_startRow(VectorStart::row(i)),
+        m_startCol(VectorStart::col(i)),
         m_blockRows(BlockRows == 1 ? 1 : xpr.rows()),
         m_blockCols(BlockCols == 1 ? 1 : xpr.cols()) {}
 
@@ -225,57 +232,6 @@
   EIGEN_DEVICE_FUNC constexpr Index rows() const { return m_blockRows.value(); }
   EIGEN_DEVICE_FUNC constexpr Index cols() const { return m_blockCols.value(); }
 
-  EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index rowId, Index colId) {
-    EIGEN_STATIC_ASSERT_LVALUE(XprType)
-    return m_xpr.coeffRef(rowId + m_startRow.value(), colId + m_startCol.value());
-  }
-
-  EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index rowId, Index colId) const {
-    return m_xpr.derived().coeffRef(rowId + m_startRow.value(), colId + m_startCol.value());
-  }
-
-  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index rowId, Index colId) const {
-    return m_xpr.coeff(rowId + m_startRow.value(), colId + m_startCol.value());
-  }
-
-  EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index) {
-    EIGEN_STATIC_ASSERT_LVALUE(XprType)
-    return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index),
-                          m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0));
-  }
-
-  EIGEN_DEVICE_FUNC inline const Scalar& coeffRef(Index index) const {
-    return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index),
-                          m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0));
-  }
-
-  EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const {
-    return m_xpr.coeff(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index),
-                       m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0));
-  }
-
-  template <int LoadMode>
-  EIGEN_DEVICE_FUNC inline PacketScalar packet(Index rowId, Index colId) const {
-    return m_xpr.template packet<Unaligned>(rowId + m_startRow.value(), colId + m_startCol.value());
-  }
-
-  template <int LoadMode>
-  EIGEN_DEVICE_FUNC inline void writePacket(Index rowId, Index colId, const PacketScalar& val) {
-    m_xpr.template writePacket<Unaligned>(rowId + m_startRow.value(), colId + m_startCol.value(), val);
-  }
-
-  template <int LoadMode>
-  EIGEN_DEVICE_FUNC inline PacketScalar packet(Index index) const {
-    return m_xpr.template packet<Unaligned>(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index),
-                                            m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0));
-  }
-
-  template <int LoadMode>
-  EIGEN_DEVICE_FUNC inline void writePacket(Index index, const PacketScalar& val) {
-    m_xpr.template writePacket<Unaligned>(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index),
-                                          m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0), val);
-  }
-
 #ifdef EIGEN_PARSED_BY_DOXYGEN
   /** \sa MapBase::data() */
   EIGEN_DEVICE_FUNC constexpr const Scalar* data() const;
@@ -309,14 +265,16 @@
     : public MapBase<Block<XprType, BlockRows, BlockCols, InnerPanel>> {
   using BlockType = Block<XprType, BlockRows, BlockCols, InnerPanel>;
   using XprTypeNested = typename internal::ref_selector<XprType>::non_const_type;
-  enum { XprTypeIsRowMajor = (int(traits<XprType>::Flags) & RowMajorBit) != 0 };
+  using VectorStart = block_vector_start<XprType, BlockRows, BlockCols>;
 
-  /** \internal Returns base+offset (unless base is null, in which case returns null).
-   * Adding an offset to nullptr is undefined behavior, so we must avoid it.
-   */
-  template <typename Scalar>
-  EIGEN_DEVICE_FUNC constexpr EIGEN_ALWAYS_INLINE static Scalar* add_to_nullable_pointer(Scalar* base, Index offset) {
-    return base != nullptr ? base + offset : nullptr;
+  /** \internal An empty block gets a null pointer: its start can lie past the end of xpr's storage. So does a block of
+   * a null xpr, since offsetting nullptr is undefined behavior. */
+  EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static auto block_data(XprType& xpr, Index startRow, Index startCol,
+                                                               Index blockRows, Index blockCols)
+      -> decltype(xpr.data()) {
+    return (blockRows == 0 || blockCols == 0 || xpr.data() == nullptr)
+               ? nullptr
+               : xpr.data() + startRow * xpr.rowStride() + startCol * xpr.colStride();
   }
 
  public:
@@ -327,51 +285,32 @@
   /** Column or Row constructor
    */
   EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl_dense(XprType& xpr, Index i)
-      : Base((BlockRows == 0 || BlockCols == 0)
-                 ? nullptr
-                 : add_to_nullable_pointer(
-                       xpr.data(),
-                       i * (((BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) && (!XprTypeIsRowMajor)) ||
-                                    ((BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) &&
-                                     (XprTypeIsRowMajor))
-                                ? xpr.innerStride()
-                                : xpr.outerStride())),
+      : Base(block_data(xpr, VectorStart::row(i), VectorStart::col(i), BlockRows == 1 ? 1 : xpr.rows(),
+                        BlockCols == 1 ? 1 : xpr.cols()),
              BlockRows == 1 ? 1 : xpr.rows(), BlockCols == 1 ? 1 : xpr.cols()),
         m_xpr(xpr),
-        m_startRow((BlockRows == 1) && (BlockCols == XprType::ColsAtCompileTime) ? i : 0),
-        m_startCol((BlockRows == XprType::RowsAtCompileTime) && (BlockCols == 1) ? i : 0) {
-    init();
-  }
+        m_startRow(VectorStart::row(i)),
+        m_startCol(VectorStart::col(i)),
+        m_outerStride(outer_stride(xpr)) {}
 
   /** Fixed-size constructor
    */
   EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl_dense(XprType& xpr, Index startRow, Index startCol)
-      : Base((BlockRows == 0 || BlockCols == 0)
-                 ? nullptr
-                 : add_to_nullable_pointer(xpr.data(),
-                                           xpr.innerStride() * (XprTypeIsRowMajor ? startCol : startRow) +
-                                               xpr.outerStride() * (XprTypeIsRowMajor ? startRow : startCol))),
+      : Base(block_data(xpr, startRow, startCol, BlockRows, BlockCols)),
         m_xpr(xpr),
         m_startRow(startRow),
-        m_startCol(startCol) {
-    init();
-  }
+        m_startCol(startCol),
+        m_outerStride(outer_stride(xpr)) {}
 
   /** Dynamic-size constructor
    */
   EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockImpl_dense(XprType& xpr, Index startRow, Index startCol, Index blockRows,
                                                         Index blockCols)
-      : Base((blockRows == 0 || blockCols == 0)
-                 ? nullptr
-                 : add_to_nullable_pointer(xpr.data(),
-                                           xpr.innerStride() * (XprTypeIsRowMajor ? startCol : startRow) +
-                                               xpr.outerStride() * (XprTypeIsRowMajor ? startRow : startCol)),
-             blockRows, blockCols),
+      : Base(block_data(xpr, startRow, startCol, blockRows, blockCols), blockRows, blockCols),
         m_xpr(xpr),
         m_startRow(startRow),
-        m_startCol(startCol) {
-    init();
-  }
+        m_startCol(startCol),
+        m_outerStride(outer_stride(xpr)) {}
 
   EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const internal::remove_all_t<XprTypeNested>& nestedExpression() const noexcept {
     return m_xpr;
@@ -392,9 +331,8 @@
   EIGEN_DEVICE_FUNC constexpr StorageIndex startCol() const noexcept { return m_startCol.value(); }
 
  protected:
-  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void init() {
-    m_outerStride =
-        internal::traits<BlockType>::HasSameStorageOrderAsXprType ? m_xpr.outerStride() : m_xpr.innerStride();
+  EIGEN_DEVICE_FUNC static constexpr Index outer_stride(const XprType& xpr) {
+    return internal::traits<BlockType>::HasSameStorageOrderAsXprType ? xpr.outerStride() : xpr.innerStride();
   }
 
   XprTypeNested m_xpr;
diff --git a/Eigen/src/Core/CoreEvaluators.h b/Eigen/src/Core/CoreEvaluators.h
index 67fe5df..975b307 100644
--- a/Eigen/src/Core/CoreEvaluators.h
+++ b/Eigen/src/Core/CoreEvaluators.h
@@ -1450,22 +1450,27 @@
                                                             : int(outer_stride_at_compile_time<ArgType>::value),
     OuterStrideAtCompileTime = HasSameStorageOrderAsArgType ? int(outer_stride_at_compile_time<ArgType>::value)
                                                             : int(inner_stride_at_compile_time<ArgType>::value),
-    // Direct-access blocks use mapbase_evaluator's contiguous loads, not the parent's packet method.
-    MaskPacketAccessBit = (InnerStrideAtCompileTime == 1 ||
-                           (!(evaluator<ArgType>::Flags & DirectAccessBit) && HasSameStorageOrderAsArgType))
-                              ? PacketAccessBit
-                              : 0,
+    // Matches block_evaluator's dispatch. Direct-access blocks use mapbase_evaluator's contiguous loads; the others
+    // forward to the parent's packet method, which only loads along the parent's inner direction.
+    ArgHasDirectAccess = bool(has_direct_access<ArgType>::value) && bool(evaluator<ArgType>::Flags & DirectAccessBit),
+    MaskPacketAccessBit =
+        (ArgHasDirectAccess ? InnerStrideAtCompileTime == 1 : bool(HasSameStorageOrderAsArgType)) ? PacketAccessBit : 0,
 
+    ArgInnerSize = ArgTypeIsRowMajor ? int(ArgType::ColsAtCompileTime) : int(ArgType::RowsAtCompileTime),
+    // InnerPanel is deduced from the parent's traits, so it only holds in the parent evaluator's storage order. A block
+    // spanning its parent's fixed inner size is an inner panel too, e.g. block<6, 4>(0, j) of a 6x6 matrix.
+    IsInnerPanel = HasSameStorageOrderAsArgType && (InnerPanel || (InnerSize != Dynamic && InnerSize == ArgInnerSize)),
     FlagsLinearAccessBit = (RowsAtCompileTime == 1 || ColsAtCompileTime == 1 ||
-                            (InnerPanel && (evaluator<ArgType>::Flags & LinearAccessBit)))
+                            (IsInnerPanel && (evaluator<ArgType>::Flags & LinearAccessBit)))
                                ? LinearAccessBit
                                : 0,
     FlagsRowMajorBit = XprType::Flags & RowMajorBit,
-    Flags0 = evaluator<ArgType>::Flags & ((HereditaryBits & ~RowMajorBit) | DirectAccessBit | MaskPacketAccessBit),
+    Flags0 = evaluator<ArgType>::Flags &
+             ((HereditaryBits & ~RowMajorBit) | (ArgHasDirectAccess ? DirectAccessBit : 0) | MaskPacketAccessBit),
     Flags = Flags0 | FlagsLinearAccessBit | FlagsRowMajorBit,
 
     PacketAlignment = unpacket_traits<PacketScalar>::alignment,
-    Alignment0 = (InnerPanel && (OuterStrideAtCompileTime != Dynamic) && (OuterStrideAtCompileTime != 0) &&
+    Alignment0 = (IsInnerPanel && (OuterStrideAtCompileTime != Dynamic) && (OuterStrideAtCompileTime != 0) &&
                   (((OuterStrideAtCompileTime * int(sizeof(Scalar))) % int(PacketAlignment)) == 0))
                      ? int(PacketAlignment)
                      : 0,
diff --git a/benchmarks/Core/bench_block_ops.cpp b/benchmarks/Core/bench_block_ops.cpp
index 1e3e137..41d8e9a 100644
--- a/benchmarks/Core/bench_block_ops.cpp
+++ b/benchmarks/Core/bench_block_ops.cpp
@@ -72,6 +72,44 @@
   state.SetBytesProcessed(state.iterations() * n * k * sizeof(Scalar));
 }
 
+// Copy and sum a fixed block spanning whole columns, which is contiguous like middleCols<4>.
+static void BM_FixedFullColumnsCopy(benchmark::State& state) {
+  Matrix<float, 6, 6> src = Matrix<float, 6, 6>::Random();
+  Matrix<float, 6, 4> dst;
+  Index j = 1;
+  for (auto _ : state) {
+    benchmark::DoNotOptimize(j);
+    dst = src.block<6, 4>(0, j);
+    benchmark::DoNotOptimize(dst.data());
+  }
+}
+
+static void BM_FixedFullColumnsSum(benchmark::State& state) {
+  Matrix<float, 6, 6> src = Matrix<float, 6, 6>::Random();
+  Index j = 1;
+  for (auto _ : state) {
+    benchmark::DoNotOptimize(j);
+    benchmark::DoNotOptimize(src.block<6, 4>(0, j).sum());
+  }
+}
+
+// Copy a block of a product, which forwards packets to the product's temporary.
+static void BM_ProductBlockCopy(benchmark::State& state) {
+  Matrix<float, 8, 8> a = Matrix<float, 8, 8>::Random(), b = Matrix<float, 8, 8>::Random();
+  Matrix<float, 8, 4> dst;
+  Index j = 1;
+  for (auto _ : state) {
+    benchmark::DoNotOptimize(j);
+    benchmark::DoNotOptimize(a.data());
+    dst = (a * b).block<8, 4>(0, j);
+    benchmark::DoNotOptimize(dst.data());
+  }
+}
+
+BENCHMARK(BM_FixedFullColumnsCopy);
+BENCHMARK(BM_FixedFullColumnsSum);
+BENCHMARK(BM_ProductBlockCopy);
+
 // (matrix_size, block_size)
 // clang-format off
 #define BLOCK_SIZES ->ArgsProduct({{256, 512, 1024}, {16, 64, 128}})
diff --git a/failtest/CMakeLists.txt b/failtest/CMakeLists.txt
index ad60168..8ab7247 100644
--- a/failtest/CMakeLists.txt
+++ b/failtest/CMakeLists.txt
@@ -126,4 +126,5 @@
 ei_add_failtest("shape_size_rows")
 ei_add_failtest("shape_size_cols")
 ei_add_failtest("numtraits_unknown_binary_precision")
+ei_add_failtest("block_linear_coeff_runtime_vector")
 ei_add_failtest_fixture()
diff --git a/failtest/block_linear_coeff_runtime_vector.cpp b/failtest/block_linear_coeff_runtime_vector.cpp
new file mode 100644
index 0000000..9f64697
--- /dev/null
+++ b/failtest/block_linear_coeff_runtime_vector.cpp
@@ -0,0 +1,18 @@
+// SPDX-FileCopyrightText: The Eigen Authors
+// SPDX-License-Identifier: MPL-2.0
+
+#include "../Eigen/Core"
+
+// A block of an expression without direct access has linear coefficient access only if it is a vector or an inner
+// panel at compile time, not merely a vector at runtime.
+#ifdef EIGEN_SHOULD_FAIL_TO_BUILD
+#define BLOCK_ROWS Dynamic
+#else
+#define BLOCK_ROWS 1
+#endif
+
+using namespace Eigen;
+
+float foo(const MatrixXf &m) { return (m + m).block<BLOCK_ROWS, 6>(1, 0, 1, 6).coeff(3); }
+
+int main() {}
diff --git a/test/block.cpp b/test/block.cpp
index e56f799..3c6c178 100644
--- a/test/block.cpp
+++ b/test/block.cpp
@@ -437,6 +437,65 @@
   VERIFY_IS_CWISE_EQUAL(inner_rows_ref, inner_rows_unwound);
 }
 
+template <typename Xpr, typename Reference>
+void check_inner_panel_like(const Xpr& xpr, const Reference& reference) {
+  VERIFY_IS_EQUAL(int(internal::evaluator<Xpr>::Flags), int(internal::evaluator<Reference>::Flags));
+  VERIFY_IS_EQUAL(int(internal::evaluator<Xpr>::Alignment), int(internal::evaluator<Reference>::Alignment));
+  VERIFY_IS_EQUAL(xpr.eval(), reference.eval());
+  VERIFY_IS_EQUAL(xpr.sum(), reference.sum());
+}
+
+// A fixed-size block spanning the whole fixed inner size of its parent is an inner
+// panel even when it is not built with InnerPanel = true.
+void inner_panel_inference_test() {
+  using ColMajor8 = Matrix<float, 8, 8, ColMajor>;
+  using RowMajor8 = Matrix<float, 8, 8, RowMajor>;
+  ColMajor8 a = ColMajor8::Random();
+  RowMajor8 b = RowMajor8::Random();
+  Index j = internal::random<Index>(0, 4);
+  VERIFY(internal::evaluator<decltype(a.block<8, 4>(0, j))>::Flags & LinearAccessBit);
+  check_inner_panel_like(a.block<8, 4>(0, j), a.middleCols<4>(j));
+  check_inner_panel_like(b.block<4, 8>(j, 0), b.middleRows<4>(j));
+  check_inner_panel_like((a + a).block<8, 4>(0, j), (a + a).middleCols<4>(j));
+  // The inferred alignment follows the parent's outer stride: 48-byte columns keep 16-byte
+  // alignment, 40-byte columns do not.
+  alignas(16) float buffer[8 * 12] = {};
+  Map<ColMajor8, Aligned16, OuterStride<12>> stride12(buffer);
+  Map<ColMajor8, Aligned16, OuterStride<10>> stride10(buffer);
+  stride12.setRandom();
+  check_inner_panel_like(stride12.block<8, 3>(0, j), stride12.middleCols<3>(j));
+  check_inner_panel_like(stride10.block<8, 3>(0, j), stride10.middleCols<3>(j));
+  // Not spanning the inner size, or spanning the outer one, is not an inner panel.
+  VERIFY(!(internal::evaluator<decltype(a.block<7, 4>(0, 0))>::Flags & LinearAccessBit));
+  VERIFY(!(internal::evaluator<decltype(a.block<4, 8>(0, 0))>::Flags & LinearAccessBit));
+}
+
+// An empty block has a null data pointer whichever constructor built it: its start can
+// lie past the end of the parent's storage.
+void empty_block_data_test() {
+  float buffer[16] = {};
+  Map<MatrixXf, 0, OuterStride<>> no_rows(buffer, 0, 3, OuterStride<>(100));
+  VERIFY(no_rows.col(2).data() == nullptr);
+  VERIFY(no_rows.block(0, 2, 0, 1).data() == nullptr);
+  Map<Matrix<float, Dynamic, Dynamic, RowMajor>, 0, OuterStride<>> no_cols(buffer, 3, 0, OuterStride<>(100));
+  VERIFY(no_cols.row(2).data() == nullptr);
+  VERIFY(no_cols.block(2, 0, 1, 0).data() == nullptr);
+}
+
+// A product evaluates into a temporary with direct access, but the product
+// expression itself has none, so its blocks forward packets to that temporary.
+void product_block_packet_access_test() {
+  using Matrix8 = Matrix<float, 8, 8>;
+  Matrix8 a = Matrix8::Random(), b = Matrix8::Random();
+  Matrix8 ab = a * b;
+  Index j = internal::random<Index>(0, 4);
+  VERIFY_IS_EQUAL(int(internal::evaluator<decltype((a * b).block<8, 4>(0, j))>::Flags & PacketAccessBit),
+                  int(internal::evaluator<Matrix8>::Flags & PacketAccessBit));
+  VERIFY(!(internal::evaluator<decltype((a * b).block<8, 4>(0, j))>::Flags & DirectAccessBit));
+  VERIFY_IS_APPROX((Matrix<float, 8, 4>((a * b).block<8, 4>(0, j))), (ab.block<8, 4>(0, j)));
+  VERIFY_IS_APPROX(MatrixXf((a * b).block(1, j, 6, 3)), MatrixXf(ab.block(1, j, 6, 3)));
+}
+
 EIGEN_DECLARE_TEST(block) {
   for (int i = 0; i < g_repeat; i++) {
     CALL_SUBTEST_1(block(Matrix<float, 1, 1>()));
@@ -453,6 +512,9 @@
     CALL_SUBTEST_9(unwind_test(MatrixXf()));
     CALL_SUBTEST_9(unwind_inner_panel_test(MatrixXf()));
     CALL_SUBTEST_9(unwind_inner_panel_test(Matrix<float, Dynamic, Dynamic, RowMajor>()));
+    CALL_SUBTEST_12(inner_panel_inference_test());
+    CALL_SUBTEST_12(empty_block_data_test());
+    CALL_SUBTEST_12(product_block_packet_access_test());
 
 #ifndef EIGEN_DEFAULT_TO_ROW_MAJOR
     CALL_SUBTEST_6(data_and_stride(MatrixXf(internal::random(5, 50), internal::random(5, 50))));
diff --git a/test/vectorization_logic.cpp b/test/vectorization_logic.cpp
index 7f50af5..9af8145 100644
--- a/test/vectorization_logic.cpp
+++ b/test/vectorization_logic.cpp
@@ -371,8 +371,10 @@
 #if !EIGEN_GCC_AND_ARCH_DOESNT_WANT_STACK_ALIGNMENT
     VERIFY(test_assign(Vector1(), Vector1(), InnerVectorizedTraversal, CompleteUnrolling));
     VERIFY(test_assign(Vector1(), Vector1() + Vector1(), InnerVectorizedTraversal, CompleteUnrolling));
+    // A full-packet segment retains alignment when inferred as an inner panel.
     VERIFY(test_assign(Vector1(), Vector1().template segment<MinVSize>(0).derived(),
-                       EIGEN_UNALIGNED_VECTORIZE ? InnerVectorizedTraversal : LinearVectorizedTraversal,
+                       EIGEN_UNALIGNED_VECTORIZE || MinVSize == PacketTraits::size ? InnerVectorizedTraversal
+                                                                                   : LinearVectorizedTraversal,
                        CompleteUnrolling));
     VERIFY(test_assign(Vector1(), Scalar(RealScalar(2.1)) * Vector1() - Vector1(), InnerVectorizedTraversal,
                        CompleteUnrolling));
@@ -380,7 +382,9 @@
         Vector1(),
         (Scalar(RealScalar(2.1)) * Vector1().template segment<MinVSize>(0) - Vector1().template segment<MinVSize>(0))
             .derived(),
-        EIGEN_UNALIGNED_VECTORIZE ? InnerVectorizedTraversal : LinearVectorizedTraversal, CompleteUnrolling));
+        EIGEN_UNALIGNED_VECTORIZE || MinVSize == PacketTraits::size ? InnerVectorizedTraversal
+                                                                    : LinearVectorizedTraversal,
+        CompleteUnrolling));
     VERIFY(test_assign(Vector1(), Vector1().cwiseProduct(Vector1()), InnerVectorizedTraversal, CompleteUnrolling));
     VERIFY(test_assign(Vector1(), Vector1().template cast<Scalar>(), InnerVectorizedTraversal, CompleteUnrolling));