Issue 238030
Summary [mlir] `convert-elementwise-to-linalg` miscompiles `arith.select` with an i1 condition and dynamically-shaped tensor operands of differing runtime extents
Labels
Assignees
Reporter lin334141-cell
    # [mlir] `convert-elementwise-to-linalg` miscompiles `arith.select` with an i1 condition and dynamically-shaped tensor operands of differing runtime extents

## Versions

- Reproduced (**executed end-to-end**, results below) on LLVM `24.0.0git` at `67005b724c917e1bdca50c82ecaa1b21a69244ed` (same-source rebuild, Release+assertions, macOS arm64) and on `main` at `61817b48e757f9a07f2a84e36326542052c12c22` (2026-10-29, local build). The responsible code is unchanged on today's main HEAD `040451d70105586ecbf77df1e5945e4d44b6f497` (2026-11-02, source-level check only — that exact build was not executed). We do not claim these are the newest available revisions.
- Independently observed by an external differential-testing pipeline on Linux x86_64: a dynamic-tensor select program with 64 frozen input frames where two compiled arms agree (`P-Q MATCH 64/64`) but both differ from an independent reference on exactly the 48 frames whose (i1) condition is false.

## Provenance note

This candidate comes from a development/regression program (D1302) of the SEMA project's dynamic-interface smoke test — not a fuzzer-generated original. The original program and its automatic variant form one root-cause cluster (both show the identical signature); the variant's exact bytes live in a sealed run root that is not archived, so only the original text is quoted.

## Description

The `arith.select` description says that with an `i1` condition "**the entire vector or tensor is chosen**" and that the un-chosen operand "is ignored, even if it was poison". Consistently, MLIR's own bufferization for `arith.select` (`mlir/lib/Dialect/Arith/Transforms/BufferizableOpInterfaceImpl.cpp`, `SelectOpInterface::bufferize`) implements exactly this **whole-value** mode for i1 conditions: it forwards one of the operand buffers (`getAliasingValues`: result `Equivalent` to both operands, `isDefinite=false`), and it explicitly rejects elementwise conditions ("Elementwise conditions are not supported yet. To bufferize such an op, it could be lowered to an elementwise linalg.generic…").

`convert-elementwise-to-linalg` (`ConvertAnyElementwiseMappableOpOnRankedTensors` in `mlir/lib/Dialect/Linalg/Transforms/ElementwiseToLinalg.cpp`) nevertheless rewrites the same op into an elementwise `linalg.generic` whose **output is the first operand**:

```mlir
// verifier-accepted input (see reproducer): %cond is an i1 scalar
%r = arith.select %cond, %a, %b : tensor<?xi8>       // %a len La=1, %b len Lb=2 at runtime

// after convert-elementwise-to-linalg (both statically tensor<?xi8>):
linalg.generic {indexing_maps = [scalar, id, id, id], iterator_types = ["parallel"]}
  ins(%cond, %a, %b : i1, tensor<?xi8>, tensor<?xi8>) outs(%a : tensor<?xi8>) {
    ^bb0(%c: i1, %x: i8, %y: i8):
      %s = arith.select %c, %x, %y : i8
      linalg.yield %s : i8
}
func.return %a
```

`getOrCreateOperandsMatchingResultTypes` reuses the first operand as the output, justified by "ElementwiseMappable guarantees that the *static* types of all tensor operands and results must have the same shape". That holds statically, but it ignores the i1 whole-value mode, in which the result must be the **chosen operand with the chosen operand's runtime shape** and the un-chosen operand must be left alone.

After `one-shot-bufferize` + `convert-linalg-to-loops` the executable becomes a loop `for i in 0..size(%a): a[i] = select(cond, a[i], b[i])` returning `%a`'s descriptor. When the two operands have **different runtime extents** this silently returns a wrong length and wrong trailing content, and it **writes into `%a`'s buffer** — an observed bufferization side effect on an input the source never writes (we report it as a side effect of this lowering; we do not claim it is a separate second defect).

Note the two official components disagree about the semantics of the same operation: the bufferization interface implements the i1 whole-value mode, while this conversion reinterprets it elementwise.

## Primary executed witness (La=1, Lb=2, cond=false)

Input (fresh, independent buffers; `%a` = `[0x80]` (1 byte), `%b` = `[0xff, 0xfe]` (2 bytes), condition = `false`):

- **Correct per the i1 whole-value semantics**: result aliases/selects `%b`: `size = 2`, data `[ff, fe]`, `%a`'s buffer untouched (`80`).
- **Observed** with `convert-elementwise-to-linalg` in the pipeline (executed): returned descriptor aliases `%a` (`alloc-differs=0`), `size = 1`, data `[ff]`, and `%a`'s buffer after the call reads `ff` (mutated from `80`).
- **Same driver, same pipeline with only `convert-elementwise-to-linalg` removed** (executed): returned descriptor aliases `%b` (`alloc-differs=1`), `size = 2`, data `[ff, fe]`, `%a`'s buffer reads `80` — correct.

## Minimal reproducer (7 lines, `min.mlir`; condition is input-dependent so it cannot be folded)

```mlir
module{func.func @choose(%a:tensor<?xi8>,%b:tensor<?xi8>,%seed:i16)->tensor<?xi8>{
%wide=arith.extsi %seed:i16 to i32
%mask=arith.constant 1:i32
%key=arith.xori %wide,%mask:i32
%zero=arith.constant 0:i32
%cond=arith.cmpi slt,%key,%zero:i32
%r=arith.select %cond,%a,%b:tensor<?xi8>
func.return %r:tensor<?xi8>
}}
```

## Commands (verified as shown; driver included)

```bash
# 1) buggy lowering (with convert-elementwise-to-linalg):
mlir-opt min.mlir --mlir-disable-threading --verify-each \
  '--pass-pipeline=builtin.module(canonicalize,convert-elementwise-to-linalg,one-shot-bufferize{bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map},convert-linalg-to-loops,convert-func-to-llvm,reconcile-unrealized-casts)' \
  -o buggy.mlir
# 2) reference lowering (same pipeline without convert-elementwise-to-linalg):
mlir-opt min.mlir --mlir-disable-threading --verify-each \
  '--pass-pipeline=builtin.module(canonicalize,one-shot-bufferize{bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map},convert-linalg-to-loops,convert-func-to-llvm,reconcile-unrealized-casts)' \
  -o ref.mlir
mlir-translate --mlir-to-llvmir ref.mlir -o ref.ll
```

`ref.ll` contains the correct whole-value selection at the descriptor level:

```llvm
%17 = llvm.select %16, %11, %5 : i1, !llvm.struct<(ptr, ptr, i64, [1 x i64], [1 x i64])>
```

Execution driver (`driver.ll`, linked with `llvm-link ref.ll driver.ll`, `llc -O2`, then a C launcher; full source in the repository copy):

```llvm
declare { ptr, ptr, i64, [1 x i64], [1 x i64] } @choose(ptr, ptr, i64, i64, i64, ptr, ptr, i64, i64, i64, i16)
@abuf = global [1 x i8] [i8 -128]   ; %a = [0x80]
@bbuf = global [2 x i8] [i8 -1, i8 -2] ; %b = [0xff, 0xfe]
define i32 @main() {
  %r = call { ptr, ptr, i64, [1 x i64], [1 x i64] } @choose(
      ptr @abuf, ptr @abuf, i64 0, i64 1, i64 1,
      ptr @bbuf, ptr @bbuf, i64 0, i64 2, i64 1, i16 3)
  ; print returned alloc/align/off/size/stride and data bytes
  ...
}
```

(With the **buggy** lowering the printed result is `alloc == @abuf, size = 1, data = "" and `@abuf` reads `ff` afterwards; with the **reference** lowering it is `alloc == @bbuf, size = 2, data = "" fe]` and `@abuf` reads `80`.)

## Expected behavior

With an i1 condition the operation chooses one operand in its entirety: the result carries the chosen operand's runtime shape and values, and the un-chosen operand is not written.

## Actual behavior

With `convert-elementwise-to-linalg` in the pipeline the compiled program returns the first operand's buffer and runtime extent; for a false condition the data is the second operand's head elements followed by the first operand's stale bytes, and the first operand's buffer is modified as a side effect.

## Semantic-boundary statement

The ODS text contains both an elementwise clause ("applies … elementwise given the shape of all operands is identical") and the i1 whole-value clause. For dynamically-shaped operands whose runtime extents differ, the two clauses can be read differently; passing the verifier does not by itself prove definedness for every dynamic input. Our reading (whole-value mode for i1 conditions) is supported by the ODS sentence, by `SelectLikeOpInterface`, and by MLIR's own bufferization implementing exactly that mode; but if maintainers instead consider mismatched runtime extents outside the defined domain for this op, we accept that reclassification — in either case the two official components (bufferization vs this conversion) currently implement conflicting semantics for the same operation.

## Upstream dedup (checked 2026-11-03)

We could not find an existing report covering this specific failure mechanism. Searches over `elementwise-to-linalg select`, `select whole tensor i1 condition`, `one-shot-bufferize select dynamic`, `arith.select dynamic shape linalg`, and related phrasings found no match; #228854 (assert in `linalg-specialize-generic-ops` on select with a captured scalar) is a different pass and failure mode. None of #237680, #237682, #236562, #236561, #234637, #228850 covers this.

## Suggested fix directions

(a) In `ConvertAnyElementwiseMappableOpOnRankedTensors`, special-case scalar-condition `arith.select`: lower via `scf.if`/select-of-descriptors (matching the bufferization interface's whole-value mode) instead of an elementwise generic with an operand as `outs`; or (b) only reuse an operand as `outs` when operand/result runtime-shape equality is guaranteed; or (c) exclude `arith.select` from this conversion until its i1 mode is representable. Happy to test a patch.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to