Skip to content

[mlir][vector] Clarify the semantics of gather/scatter indexing (nfc) - #181357

Open
banach-space wants to merge 6 commits into
llvm:mainfrom
banach-space:andrzej/clarify_gather_scatter_index_sema
Open

banach-space wants to merge 6 commits into
llvm:mainfrom
banach-space:andrzej/clarify_gather_scatter_index_sema

Conversation

@banach-space

@banach-space banach-space commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

@llvmbot

llvmbot commented Feb 13, 2026

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-mlir

Author: Andrzej Warzyński (banach-space)

Changes

For context, see:

Currently, ConvertVectorToLLVM rejects strided memrefs when lowering
vector.gather and vector.scatter. This PR adds tests to document
that behavior.

Supporting strided memrefs in the lowering is left as future work.
However, it is still unclear whether gather/scatter on strided memrefs
should be supported at all (see the Discourse discussion above).

This PR also adds tests for vector.load and vector.store in
invalid.mlir to document that these ops do not support strided
memrefs.


Full diff: https://github.com/llvm/llvm-project/pull/181357.diff

4 Files Affected:

  • (modified) mlir/include/mlir/Dialect/Vector/IR/VectorOps.td (+9-1)
  • (modified) mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp (+2)
  • (modified) mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir (+27)
  • (modified) mlir/test/Dialect/Vector/invalid.mlir (+17)
diff --git a/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td b/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
index ddb04b6bbe40d..f49c578c91092 100644
--- a/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
+++ b/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
@@ -2087,7 +2087,10 @@ def Vector_GatherOp :
     result[i,j] := if mask[i,j] then base[i0, i1, i2 + indices[i,j]]
                    else pass_thru[i,j]
     ```
-    The index into `base` only varies in the innermost ((k-1)-th) dimension.
+    The index into `base` only varies in the innermost ((k-1)-th) dimension and
+    is treated as a logical rather than a physical index, i.e. it does not
+    encode any potential non-identity strides in the underlying MemRef layout
+    (Tensors do not model strided layouts, so only logical indexing is possible).
 
     If a mask bit is set and the corresponding index is out-of-bounds for the
     given base, the behavior is undefined. If a mask bit is not set, the value
@@ -2180,6 +2183,11 @@ def Vector_ScatterOp
     is stored regardless of the index, and the index is allowed to be
     out-of-bounds.
 
+    The index into `base` only varies in the innermost ((k-1)-th) dimension and
+    is treated as a logical rather than a physical index, i.e. it does not
+    encode any potential non-identity strides in the underlying MemRef layout
+    (Tensors do not model strided layouts, so only logical indexing is possible).
+
     If the index vector contains two or more duplicate indices, the behavior is
     undefined. Underlying implementation may enforce strict sequential
     semantics.
diff --git a/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp b/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp
index 05d541fe80356..0a255c853b07e 100644
--- a/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp
+++ b/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp
@@ -290,6 +290,7 @@ class VectorGatherOpConversion
     MemRefType memRefType = dyn_cast<MemRefType>(gather.getBaseType());
     assert(memRefType && "The base should be bufferized");
 
+    // TODO: Add support for strided MemRef.
     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
       return rewriter.notifyMatchFailure(gather, "memref type not supported");
 
@@ -348,6 +349,7 @@ class VectorScatterOpConversion
     auto memRefType = dyn_cast<MemRefType>(scatter.getBaseType());
     assert(memRefType && "The base should be bufferized");
 
+    // TODO: Add support for strided MemRef.
     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
       return rewriter.notifyMatchFailure(scatter, "memref type not supported");
 
diff --git a/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir b/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir
index cb48ca3374e8d..3d075fe3b24ee 100644
--- a/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir
+++ b/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir
@@ -2052,6 +2052,20 @@ func.func @gather_with_alignment(%arg0: memref<?xf32>, %arg1: vector<3xi32>, %ar
 
 // -----
 
+// TODO: Implement this lowering.
+func.func @negative_gather_on_strided_memref(%arg0: memref<?xf32, strided<[2], offset: ?>>, %arg1: vector<3xi32>, %arg2: vector<3xi1>, %arg3: vector<3xf32>) -> vector<3xf32> {
+  %0 = arith.constant 0: index
+  %1 = vector.gather %arg0[%0][%arg1], %arg2, %arg3
+    : memref<?xf32, strided<[2], offset: ?>>, vector<3xi32>, vector<3xi1>, vector<3xf32> into vector<3xf32>
+  return %1 : vector<3xf32>
+}
+
+// CHECK-LABEL: func @negative_gather_on_strided_memref
+// CHECK-NOT: llvm.intr.masked.gather
+// CHECK: vector.gather
+
+// -----
+
 //===----------------------------------------------------------------------===//
 // vector.scatter
 //===----------------------------------------------------------------------===//
@@ -2138,6 +2152,19 @@ func.func @scatter_with_alignment(%arg0: memref<?xf32>, %arg1: vector<3xi32>, %a
 // CHECK-LABEL: func @scatter_with_alignment
 // CHECK: llvm.intr.masked.scatter %{{.*}}, %{{.*}}, %{{.*}} {alignment = 8 : i32} : vector<3xf32>, vector<3xi1> into vector<3x!llvm.ptr>
 
+// -----
+
+// TODO: Implement this lowering.
+func.func @negative_scatter_on_strided_memref(%arg0: memref<?xf32, strided<[2], offset: ?>>, %arg1: vector<3xi32>, %arg2: vector<3xi1>, %arg3: vector<3xf32>) {
+  %0 = arith.constant 0: index
+  vector.scatter %arg0[%0][%arg1], %arg2, %arg3
+    : memref<?xf32, strided<[2], offset: ?>>, vector<3xi32>, vector<3xi1>, vector<3xf32>
+  return
+}
+
+// CHECK-LABEL: func @negative_scatter_on_strided_memref
+// CHECK-NOT: llvm.intr.masked.scatter
+// CHECK: vector.scatter
 
 // -----
 
diff --git a/mlir/test/Dialect/Vector/invalid.mlir b/mlir/test/Dialect/Vector/invalid.mlir
index 28e1206ff3d0a..94cb0fe70d3fc 100644
--- a/mlir/test/Dialect/Vector/invalid.mlir
+++ b/mlir/test/Dialect/Vector/invalid.mlir
@@ -2038,6 +2038,15 @@ func.func @load_non_pow_of_2_alignment(%memref: memref<4xi32>, %c0: index) {
 
 // -----
 
+func.func @load_non_unit_stride(%src : memref<?xi8, strided<[2], offset: ?>>) {
+  %c0 = arith.constant 0 : index
+  // expected-error @+1 {{'vector.load' op most minor memref dim must have unit stride}}
+  %0 = vector.load %src[%c0] : memref<?xi8, strided<[2], offset: ?>>, vector<16xi8>
+  return
+}
+
+// -----
+
 //===----------------------------------------------------------------------===//
 // vector.store
 //===----------------------------------------------------------------------===//
@@ -2064,3 +2073,11 @@ func.func @store_non_pow_of_2_alignment(%memref: memref<4xi32>, %val: vector<4xi
   vector.store %val, %memref[%c0] { alignment = 3 } : memref<4xi32>, vector<4xi32>
   return
 }
+
+// -----
+
+func.func @store_non_unit_stride(%src : memref<?xi8, strided<[2], offset:?>>,%val : vector<16xi8>, %c0: index) {
+  // expected-error @below {{'vector.store' op most minor memref dim must have unit stride}}
+  vector.store %val, %src[%c0] : memref<?xi8, strided<[2], offset: ?>>, vector<16xi8>
+  return
+}

@llvmbot

llvmbot commented Feb 13, 2026

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-mlir-vector

Author: Andrzej Warzyński (banach-space)

Changes

For context, see:

Currently, ConvertVectorToLLVM rejects strided memrefs when lowering
vector.gather and vector.scatter. This PR adds tests to document
that behavior.

Supporting strided memrefs in the lowering is left as future work.
However, it is still unclear whether gather/scatter on strided memrefs
should be supported at all (see the Discourse discussion above).

This PR also adds tests for vector.load and vector.store in
invalid.mlir to document that these ops do not support strided
memrefs.


Full diff: https://github.com/llvm/llvm-project/pull/181357.diff

4 Files Affected:

  • (modified) mlir/include/mlir/Dialect/Vector/IR/VectorOps.td (+9-1)
  • (modified) mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp (+2)
  • (modified) mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir (+27)
  • (modified) mlir/test/Dialect/Vector/invalid.mlir (+17)
diff --git a/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td b/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
index ddb04b6bbe40d..f49c578c91092 100644
--- a/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
+++ b/mlir/include/mlir/Dialect/Vector/IR/VectorOps.td
@@ -2087,7 +2087,10 @@ def Vector_GatherOp :
     result[i,j] := if mask[i,j] then base[i0, i1, i2 + indices[i,j]]
                    else pass_thru[i,j]
     ```
-    The index into `base` only varies in the innermost ((k-1)-th) dimension.
+    The index into `base` only varies in the innermost ((k-1)-th) dimension and
+    is treated as a logical rather than a physical index, i.e. it does not
+    encode any potential non-identity strides in the underlying MemRef layout
+    (Tensors do not model strided layouts, so only logical indexing is possible).
 
     If a mask bit is set and the corresponding index is out-of-bounds for the
     given base, the behavior is undefined. If a mask bit is not set, the value
@@ -2180,6 +2183,11 @@ def Vector_ScatterOp
     is stored regardless of the index, and the index is allowed to be
     out-of-bounds.
 
+    The index into `base` only varies in the innermost ((k-1)-th) dimension and
+    is treated as a logical rather than a physical index, i.e. it does not
+    encode any potential non-identity strides in the underlying MemRef layout
+    (Tensors do not model strided layouts, so only logical indexing is possible).
+
     If the index vector contains two or more duplicate indices, the behavior is
     undefined. Underlying implementation may enforce strict sequential
     semantics.
diff --git a/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp b/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp
index 05d541fe80356..0a255c853b07e 100644
--- a/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp
+++ b/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp
@@ -290,6 +290,7 @@ class VectorGatherOpConversion
     MemRefType memRefType = dyn_cast<MemRefType>(gather.getBaseType());
     assert(memRefType && "The base should be bufferized");
 
+    // TODO: Add support for strided MemRef.
     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
       return rewriter.notifyMatchFailure(gather, "memref type not supported");
 
@@ -348,6 +349,7 @@ class VectorScatterOpConversion
     auto memRefType = dyn_cast<MemRefType>(scatter.getBaseType());
     assert(memRefType && "The base should be bufferized");
 
+    // TODO: Add support for strided MemRef.
     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
       return rewriter.notifyMatchFailure(scatter, "memref type not supported");
 
diff --git a/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir b/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir
index cb48ca3374e8d..3d075fe3b24ee 100644
--- a/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir
+++ b/mlir/test/Conversion/VectorToLLVM/vector-to-llvm-interface.mlir
@@ -2052,6 +2052,20 @@ func.func @gather_with_alignment(%arg0: memref<?xf32>, %arg1: vector<3xi32>, %ar
 
 // -----
 
+// TODO: Implement this lowering.
+func.func @negative_gather_on_strided_memref(%arg0: memref<?xf32, strided<[2], offset: ?>>, %arg1: vector<3xi32>, %arg2: vector<3xi1>, %arg3: vector<3xf32>) -> vector<3xf32> {
+  %0 = arith.constant 0: index
+  %1 = vector.gather %arg0[%0][%arg1], %arg2, %arg3
+    : memref<?xf32, strided<[2], offset: ?>>, vector<3xi32>, vector<3xi1>, vector<3xf32> into vector<3xf32>
+  return %1 : vector<3xf32>
+}
+
+// CHECK-LABEL: func @negative_gather_on_strided_memref
+// CHECK-NOT: llvm.intr.masked.gather
+// CHECK: vector.gather
+
+// -----
+
 //===----------------------------------------------------------------------===//
 // vector.scatter
 //===----------------------------------------------------------------------===//
@@ -2138,6 +2152,19 @@ func.func @scatter_with_alignment(%arg0: memref<?xf32>, %arg1: vector<3xi32>, %a
 // CHECK-LABEL: func @scatter_with_alignment
 // CHECK: llvm.intr.masked.scatter %{{.*}}, %{{.*}}, %{{.*}} {alignment = 8 : i32} : vector<3xf32>, vector<3xi1> into vector<3x!llvm.ptr>
 
+// -----
+
+// TODO: Implement this lowering.
+func.func @negative_scatter_on_strided_memref(%arg0: memref<?xf32, strided<[2], offset: ?>>, %arg1: vector<3xi32>, %arg2: vector<3xi1>, %arg3: vector<3xf32>) {
+  %0 = arith.constant 0: index
+  vector.scatter %arg0[%0][%arg1], %arg2, %arg3
+    : memref<?xf32, strided<[2], offset: ?>>, vector<3xi32>, vector<3xi1>, vector<3xf32>
+  return
+}
+
+// CHECK-LABEL: func @negative_scatter_on_strided_memref
+// CHECK-NOT: llvm.intr.masked.scatter
+// CHECK: vector.scatter
 
 // -----
 
diff --git a/mlir/test/Dialect/Vector/invalid.mlir b/mlir/test/Dialect/Vector/invalid.mlir
index 28e1206ff3d0a..94cb0fe70d3fc 100644
--- a/mlir/test/Dialect/Vector/invalid.mlir
+++ b/mlir/test/Dialect/Vector/invalid.mlir
@@ -2038,6 +2038,15 @@ func.func @load_non_pow_of_2_alignment(%memref: memref<4xi32>, %c0: index) {
 
 // -----
 
+func.func @load_non_unit_stride(%src : memref<?xi8, strided<[2], offset: ?>>) {
+  %c0 = arith.constant 0 : index
+  // expected-error @+1 {{'vector.load' op most minor memref dim must have unit stride}}
+  %0 = vector.load %src[%c0] : memref<?xi8, strided<[2], offset: ?>>, vector<16xi8>
+  return
+}
+
+// -----
+
 //===----------------------------------------------------------------------===//
 // vector.store
 //===----------------------------------------------------------------------===//
@@ -2064,3 +2073,11 @@ func.func @store_non_pow_of_2_alignment(%memref: memref<4xi32>, %val: vector<4xi
   vector.store %val, %memref[%c0] { alignment = 3 } : memref<4xi32>, vector<4xi32>
   return
 }
+
+// -----
+
+func.func @store_non_unit_stride(%src : memref<?xi8, strided<[2], offset:?>>,%val : vector<16xi8>, %c0: index) {
+  // expected-error @below {{'vector.store' op most minor memref dim must have unit stride}}
+  vector.store %val, %src[%c0] : memref<?xi8, strided<[2], offset: ?>>, vector<16xi8>
+  return
+}

Comment on lines +2090 to +2092
The index into `base` only varies in the innermost ((k-1)-th) dimension and
is treated as a logical rather than a physical index, i.e. it does not
encode any potential non-identity strides in the underlying MemRef layout

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure the 'physical index' term is well-understood in general (physical addressing is also a thing and mostly orthogonal to this) -- maybe better to say what it is wrt to strides

Suggested change
The index into `base` only varies in the innermost ((k-1)-th) dimension and
is treated as a logical rather than a physical index, i.e. it does not
encode any potential non-identity strides in the underlying MemRef layout
The access into `base` is contiguous within the innermost ((k-1)-th) dimension and
does not account for any potential non-identity strides in the underlying MemRef layout

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

The access into `base` is contiguous within the innermost ((k-1)-th) dimension a

This wouldn't be accurate - the point of vector.gather is that we can load non-contiguous elements. Let me try rephrasing while incorporating your suggestion.

This might take us a few iterations 😅

@krzysz00

Copy link
Copy Markdown
Contributor

Re the "it only varies in the innermost dimension" (however we're phrasing that) - I'm not sure that's consistent with existing usage up in lowerings from linalg

That being said, I personally think that the high-level fix is to make the vector of offsets take K-tuples of indices (where 1 <= K < rank(base)) that indicate the index to be gathered along in the each of the K trailing dimensions of the memref - where, for backwards compatibility and ergonomics, we omit the x1part of the[out shape]x1xindex` that previous extension implies - and make that a canonical form).

@banach-space

Copy link
Copy Markdown
Contributor Author

Re the "it only varies in the innermost dimension" (however we're phrasing that) - I'm not sure that's consistent with existing usage up in lowerings from linalg

The original wording risked implying a lowering decision; that’s why I removed it and replaced it with the concrete description:

indices are element offsets - they are expressed in units of elements (not bytes). The offset is added to the underlying memory address

I used "logical indexing" in my original commit (to match my RFC), but Jakub pointed out that we should try something clearer. Hopefully the updated version works!

As for "consistency with lowering from Linalg" - that would be referring to the vectorization of tensor.extract, right? Is it really inconsistent? Could you share a specific example?

That being said, I personally think that the high-level fix is to make the vector of offsets take K-tuples of indices (where 1 <= K < rank(base)) that indicate the index to be gathered along in the each of the K trailing dimensions of the memref - where, for backwards compatibility and ergonomics, we omit the x1part of the[out shape]x1xindex` that previous extension implies - and make that a canonical form).

That would be a high-level change along the lines of https://discourse.llvm.org/t/rfc-improving-gather-codegen-for-vector-dialect? I feel that Discourse is more suitable for such a high-level discussion. As per the title of my PR, I merely want to clarify the existing semantics 😅

Thanks for all the discussion so far!

@banach-space

Copy link
Copy Markdown
Contributor Author

Ping

@krzysz00

krzysz00 commented Mar 2, 2026

Copy link
Copy Markdown
Contributor

@banach-space Re your question about Linalg, the code I'm thinking of - which is doing a bunch of multiplies - is

static Value calculateGatherOffset(RewriterBase &rewriter,
.

elements (not bytes). The offset is added to the underlying memory address,
so if the resulting position exceeds the size of the innermost dimension,
it naturally advances into the next row and/or plane according to the
identity (row-major) layout of 3D `base` (col = dim 0, row = dim 1, plane

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this mentioning 3D?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The running example in the docs is 3D: https://mlir.llvm.org/docs/Dialects/Vector/#vectorgather-vectorgatherop

I can see how this could be confusing though, so let me tweak a bit.

@banach-space

Copy link
Copy Markdown
Contributor Author

@banach-space Re your question about Linalg, the code I'm thinking of - which is doing a bunch of multiplies - is

Thanks! I am familiar with that implementation - I wrote it. I don't quite see where the consistency is? Why is the presence of multiplies significant here?

To make the discussion a bit more concrete, here is an example:

func.func @example(%src:tensor<24x80x16xf32>, %offset: index, %output : tensor<2x1x4xf32>) -> tensor<2x1x4xf32> {
  %c13 = arith.constant 13 : index
  %1 = linalg.generic {
    indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, d2)>],
    iterator_types = ["parallel", "parallel", "parallel"]
  } outs(%output : tensor<2x1x4xf32>) {
  ^bb0(%out: f32):

    %idx_0 = linalg.index 0 : index
    %idx_0_p_2 = affine.apply affine_map<(d0) -> (d0 + 2)>(%idx_0)

    %idx_2 = linalg.index 2 : index
    %idx_2_p_off = affine.apply affine_map<(d0, d1) -> (d0 + d1)>(%idx_2, %offset)

    %val = tensor.extract %src[%idx_0_p_2, %idx_2_p_off, %c13] : tensor<24x80x16xf32>

    linalg.yield %val : f32
  } -> tensor<2x1x4xf32>
  return %1 : tensor<2x1x4xf32>
}

module @transforms attributes { transform.with_named_sequence } {
  transform.named_sequence @__transform_main(%module: !transform.any_op {transform.readonly}) {

    %0 = transform.structured.match ops{["linalg.generic"]} in %module : (!transform.any_op) -> !transform.any_op
    %1 = transform.get_parent_op %0 {isolated_from_above} : (!transform.any_op) -> !transform.any_op
    %2 = transform.structured.vectorize_children_and_apply_patterns %1 { vectorize_nd_extract } : (!transform.any_op) -> !transform.any_op

    transform.yield
   }
}

It vectorizes as:

  func.func @vectorize_nd_tensor_extract_with_affine_apply_gather(%arg0: tensor<24x80x16xf32>, %arg1: index, %arg2: tensor<2x1x4xf32>) -> tensor<2x1x4xf32> {
    %cst = arith.constant dense<13> : vector<2x1x4xindex>
    %cst_0 = arith.constant dense<16> : vector<2x1x4xindex>
    %cst_1 = arith.constant dense<[160, 240]> : vector<2xindex>
    %c0 = arith.constant 0 : index
    %cst_2 = arith.constant dense<0.000000e+00> : vector<2x1x4xf32>
    %cst_3 = arith.constant dense<true> : vector<2x1x4xi1>
    %cst_4 = arith.constant dense<[0, 1, 2, 3]> : vector<4xindex>
    %0 = vector.broadcast %arg1 : index to vector<4xindex>
    %1 = arith.addi %0, %cst_4 : vector<4xindex>
    %2 = vector.broadcast %cst_1 : vector<2xindex> to vector<4x1x2xindex>
    %3 = vector.transpose %2, [2, 1, 0] : vector<4x1x2xindex> to vector<2x1x4xindex>
    %4 = vector.broadcast %1 : vector<4xindex> to vector<2x1x4xindex>
    %5 = arith.addi %4, %3 : vector<2x1x4xindex>
    %6 = arith.muli %5, %cst_0 : vector<2x1x4xindex>
    %7 = arith.addi %6, %cst : vector<2x1x4xindex>
    %8 = vector.gather %arg0[%c0, %c0, %c0] [%7], %cst_3, %cst_2 : tensor<24x80x16xf32>, vector<2x1x4xindex>, vector<2x1x4xi1>, vector<2x1x4xf32> into vector<2x1x4xf32>
    %9 = vector.transfer_write %8, %arg2[%c0, %c0, %c0] {in_bounds = [true, true, true]} : vector<2x1x4xf32>, tensor<2x1x4xf32>
    return %9 : tensor<2x1x4xf32>
  }

This looks OK to me - a vector of indices, one per output element in the output vector, is fed into vector.gather:

%7 = arith.addi %6, %cst : vector<2x1x4xindex>
%8 = vector.gather %arg0[%c0, %c0, %c0] [%7], %cst_3, %cst_2 : tensor<24x80x16xf32>, vector<2x1x4xindex>, vector<2x1x4xi1>, vector<2x1x4xf32> into vector<2x1x4xf32>

Could you point me at the inconsistency that you are referring to? That would really help.

Let me also note, the documentation of vector.gather and vector.scatter pre-dates the implementation in the Linalg vectorizer. It is for the vectorizer to implement what is in the docs, rather than the docs reflect what the vectorizer does. If that is not the case, I'd be happy to fix that.

@banach-space

Copy link
Copy Markdown
Contributor Author

Ping @kuhar @krzysz00

This PR only aims to:

If you think either of these goals is not met, please let me know. Otherwise, if there are no objections, I would plan to land this so we can close the loop on the semantics discussion.

Btw, @krzysz00 - I’m happy to continue the discussion about the inconsistency. However, I don’t think this PR changes much in that regard; it simply rephrases the current documentation and adds tests capturing the existing semantics, without modifying the behaviour itself.

@krzysz00

Copy link
Copy Markdown
Contributor
  1. The inconsistency has been fixed with your updates stating that the gather indices don't follow layout but continue in a dense, row-major way. I don't know if those should be the semantics, given that tensor.extract_strided_slice / memref.subview exist - but that is what we're trying to document here.
  2. I'd like to flag [mlir][vector] Lower vector.gather with delinearization approach #184706 and @hanhanW because I think we'll be getting inconsistent semantics again from that change
  3. I'm going to once again suggest that we should make gather take k <= rank -tuples of indices to fix this mess.

@banach-space

Copy link
Copy Markdown
Contributor Author
  1. The inconsistency has been fixed with your updates stating that the gather indices don't follow layout but continue in a dense, row-major way. I don't know if those should be the semantics, given that tensor.extract_strided_slice / memref.subview exist - but that is what we're trying to document here.

Thanks!

  1. I'd like to flag [mlir][vector] Lower vector.gather with delinearization approach #184706 and @hanhanW because I think we'll be getting inconsistent semantics again from that change

I'm not sure what inconsistency you are referring to, so I would appreciate if you could be more specific. As mentioned in my reply in that PR, I believe that this PR and @hanhanW's PR are consistent.

  1. I'm going to once again suggest that we should make gather take k <= rank -tuples of indices to fix this mess.

The intent of this PR is to clarify the existing semantics. You are of course welcome to propose a change to the op's design if you think that would be a better long-term solution.

In the meantime, I assume that you agree that this PR implements what we (including yourself) agreed on in https://discourse.llvm.org/t/rfc-semantics-of-vector-gather-indices-with-strided-memrefs/89722 - I have not seen any comments stating otherwise.

@krzysz00

Copy link
Copy Markdown
Contributor

So, this PR implements the semantics I was pushing for initially with its "going off the end of the last dimension proceeds as if in the identity layout" wording.

That definition doesn't match the lowering implemented in #184706 , which attempts to account for the multi-dimensionality of the memref, and has semantics that are meaningfully different from lowering directly to something like LLVM's gather.

I also had the sense that your initial RFC was disagreeing with the sort of "ignore subviews" indexing I'd been calling for when I first tried to clarify vector.gather semantics, and now we've ended up back where I started.

So, to state the question:

%indices = <0, 1, 2, 3> : vector<4xindex>
%res = vector.gather %memref[%c0, %c0], %indices : memref<2x2xf32, strided[128, 1]> to vector<4xf32>

If we let float* base be the base of %memref there (so that logical indexing works), is it

%res = <base[0], base[1], base[2], base[3]>

as your documentation update and VectorToLLVM suggests, or

%res = <base[0], base[1], base[128], base[129]>

as the new delinearization-based change suggests?

@krzysz00

Copy link
Copy Markdown
Contributor

Also, my recollection of the RFC was that we were explicitly leaving the case I'm asking about as undefined behavior - as in, you're not allowed to do that currently - because of this exact bit of confusion.

For context, see:
* https://discourse.llvm.org/t/rfc-semantics-of-vector-gather-indices-with-strided-memrefs

Currently, `ConvertVectorToLLVM` rejects strided memrefs when lowering
`vector.gather` and `vector.scatter`. This PR adds tests to document
that behavior.

Supporting strided memrefs in the lowering is left as future work.
However, it is still unclear whether gather/scatter on strided memrefs
should be supported at all (see the Discourse discussion above).

This PR also adds tests for `vector.load` and `vector.store` in
`invalid.mlir` to document that these ops do not support strided
memrefs.
@banach-space
banach-space force-pushed the andrzej/clarify_gather_scatter_index_sema branch from b0dff97 to fd02f73 Compare March 17, 2026 10:07
@banach-space

Copy link
Copy Markdown
Contributor Author

UPDATE 17/3/26 In order to de-noise this PR, I have moved test changes to #186990.

@banach-space

Copy link
Copy Markdown
Contributor Author

So, this PR implements the semantics I was pushing for initially with its "going off the end of the last dimension proceeds as if in the identity layout" wording.

Just to clarify: this PR does not implement new semantics - these are NFC documentation changes.

(see also my comment below re: trimming this patch)

That definition doesn't match the lowering implemented in #184706 , which attempts to account for the multi-dimensionality of the memref

That PR addresses the lowering of vector.gather to vector.load. During this lowering (vector.gather→vector.load`), the semantics previously captured by vector.gather need to be re-expressed, which is where the linearization/delinearization comes in.

In particular, this accounts for:

  • the multi-dimensionality of the memref, and
  • the loss of the index argument (which only exists on vector.gather).

Effectively, the (offset, index) pair is replaced by a single offset. So while the mechanism differs, I believe the semantics remain consistent.

That said, I’m happy to take a step back and trim the part of this PR where we don’t yet have agreement - see this commit: 9513d44. Thanks for pointing that out.

Just to make sure I understand your concern correctly: are you disagreeing with the direction taken in #184706, or with the "logical vs physical" index distinction from the RFC discussion? Are you OK with the current wording in this PR?

has semantics that are meaningfully different from lowering directly to something like LLVM's gather.

Good catch - that should indeed be fixed.


Given the confusion and the length of the review (~1 month), I’d like to bring in more eyes.

@rengolin - since you participated in the Discourse discussion, would you mind taking a look?

(As per Jakub’s suggestion, I’ve avoided using “physical” vs “logical” terminology in the docs.)

in units of elements from the starting element, i.e. `%base[%ofs_0, %ofs_1,
%ofs_2]` for the example above. Importantly, for MemRefs, `indices` are
%interpreted assuming an identity (contiguous) MemRef
layout and do not account for non-identity strides.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does do not account mean?

Is it an error (and therefore needs to update the verifier)? Or does it just ignore the stride and take from outside of the domain (and therefore becomes undefined behaviour)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By “do not account”, I mean that the indices are interpreted purely in terms of logical element offsets, independent of the MemRef’s physical layout.

In particular:

  • this is not an error, and does not require verifier changes, and
  • the semantics are defined in terms of the logical view of the MemRef, as if it had an identity (contiguous) layout.

Any non-identity layout (i.e. strides) is handled during lowering, where the logical indexing is mapped to physical addresses.

I’ll update the wording to make this clearer.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I'd like to be clear that I don't like the "you have to unfold the index according to the shape of the memref" semantics that are being proposed here - they make the lowering of what's supposed to be a low-level operation extremely non-trivial, and make rewrites (such as folding in a subview) a rather painful pile of index computations.

This is why I'm pushing for "the index just gets added to the last dimension, and if that goes oob, so be it" and the handling of, say, gathering along multiple dimensions involving either k vectors of indices (one per dimension) or a vector of k indices per vector element.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • the semantics are defined in terms of the logical view of the MemRef, as if it had an identity (contiguous) layout.

So:

  %value: memref<10x10xf32, stride=[64,64]>
  %indices: vector<2x3xi32>
  %mask: vector<2x3xi1>
  %pass_thru: vector<2x3xf32>)
  %result = vector.gather %base[9, 9][%indices], %mask, %pass_thru : ...

will read OOB?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Depends on the contents of indices.

I'm also going to add the argument against the delinearizaiton semantics that vector.load %m[%x] : memref<?xT>, vector<NxT> is exactly equivalent to

vector.gather %m[%x][seq(0, N)] mask = broadcast(true), passthrough = broadcast(poison) : memref<?xT>, vector<Nxindex>, vector<Nxi1>, vector<NxT> -> vector<NxT>

including OOB semantics

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test case for the inconsistency #187071 (comment)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will read OOB?

If your indices are > 0 and mask is "all true", then OOB, yes. At least based on the available context.

I guess that you could consider %value to be a view into a larger source MemRef and in the context of that MemRef it would possibly be OK? I think that we should stick with the "local" view though.

Test case for the inconsistency #187071 (comment)

Thanks! I created #187215 so that we have one central place to discuss that and so that there's a repro that people can use.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clearer now, thanks!

This branch was previously deployed

1 inactive (outdated) deployment
main-branch-only — cb888238 Deployed Feb 13, 2026 by llvmbot via auto-subscribe #171755
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants