Issue 238236
Summary [mlir][tosa] `tosa-to-linalg` miscompiles `tosa.rescale` with EXT-DYNAMIC when exactly one of multiplier/shift is constant
Labels mlir
Assignees
Reporter lin334141-cell
    # [mlir][tosa] `tosa-to-linalg` miscompiles `tosa.rescale` when exactly one of multiplier/shift is constant (EXT-DYNAMIC)

## Versions

- Reproduced (**executed**) with LLVM `24.0.0git` at `67005b724c917e1bdca50c82ecaa1b21a69244ed` (`mlir-opt` + `mlir-translate`, same-source rebuild, Release+assertions, macOS arm64).
- The responsible code is **unchanged** on today's `main` HEAD `b58145793359` (2026-11-03, source-level check only — that build was **not** executed here).
- Independently observed by an external differential-testing pipeline on Linux x86_64 with two separate new-source programs (one with a runtime `[1]xi32` multiplier and constant `shift=30`, one with a constant multiplier and runtime `shift`), each reporting the same signature against an independent reference. Four candidate IDs from that pipeline (two method-side, two scope-side) trace to this one root cause; they are evidence locations, not four defects.
- Provenance: the mixed-case handling traces to PR #155967 ("[mlir][tosa] Support RescaleOp with dynamic extension in TosaToLinalg", merged 2025-10-14). We have **not** performed a full version bisection; the only executed reproduction is the 67005b72 rebuild below.
- Original-evidence caveat: the pipeline's per-frame run-root evidence (task inputs, references, P/Q raw observations, lowered IR per call) was not byte-verified by us in full; we rely on the aggregate difference counts (31/41 and 12/15 frames) and the quoted sample bit patterns, which our independent computation and reproduction explain exactly.

## Description

With TOSA `EXT-DYNAMIC` (non-constant quantization parameters), `RescaleConverter` in `mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp` only fills the constant-value lists when **both** the multiplier and the shift are constant:

```cpp
llvm::SmallVector<int32_t> shiftValues;
llvm::SmallVector<int32_t> multiplierValues;
if (isMultiplierConstant && isShiftConstant) {   // ← only filled in this case
  shiftValues = ...;
  multiplierValues = ...;
} else
  doubleRound = ...;
...
setupLinalgGenericOpInputAndIndexingMap(rewriter, multiplierValues, ..., isMultiplierConstant, ...);
setupLinalgGenericOpInputAndIndexingMap(rewriter, shiftValues,     ..., isShiftConstant,     ...);
```

The two helper calls then decide independently, per side, whether to treat that operand as a constant. In the **mixed** case (one constant, one dynamic) the constant side therefore has `values.empty() == true` while `isConstant == true`, and the helper takes its "constant" `else` branch:

```cpp
auto tensorType = RankedTensorType::get({values.size()}, elementType);  // {0} → tensor<0xi8> / tensor<0xi32>
return arith::ConstantOp::create(rewriter, loc, DenseIntElementsAttr::get(tensorType, ...));  // dense<>
...
indexingMaps.push_back(AffineMap::get(rank, 0, exprs, ctx));   // identity map, not a broadcast
```

The constant side is emitted as a **zero-element tensor** (`arith.constant dense<> : tensor<0xi8>` / `tensor<0xi32>`) with an **identity indexing map** instead of a broadcast map. The `linalg.generic` body then reads `shift`/`multiplier` from that empty buffer — an out-of-bounds access whose value is undefined. In the executed reproducer this undefined value behaves as `0` (and the pipeline also ignores the original constant operand entirely, leaving it dead), so the rescale degenerates to a bare multiply with no shift and no rounding: e.g. `apply_scale_32(1, 2^30, 30)` returns `2^30` instead of `1`. Whether the undefined read deterministically yields `0` in every layout is not claimed; the executed reproducers consistently show it, and the recorded A100/S007 aggregate signatures (31/41 and 12/15 frames differing by exactly the missing `>> shift`) are consistent with it.

## Definedness (TOSA 1.0.1 `apply_scale_32`)

The minimal reproducer satisfies every precondition of the TOSA 1.0.1 `RESCALE` contract for `apply_scale_32` (`SINGLE_ROUND`, `scale32 = true`):

- **`2 <= shift <= 62`**: the witness uses `shift = 30`. (The upper bound allows decomposition into two 31-bit right shifts; values above 62 are outside the spec domain.)
- **`multiplier >= 0`**: the witness uses `multiplier = 2^30`.
- **`-2^(shift-1) <= value < 2^(shift-1)`**: the witness values `{1, -1, -2, 3}` lie in `[-2^29, 2^29)` for `shift = 30`.
- Input/output are `i32` and the result is guaranteed representable in int32 (the spec's 64-bit accumulator never overflows under these preconditions).

Under these preconditions `apply_scale_32` is **total**, and for `multiplier = 2^30, shift = 30` it is exactly the identity — verified with Python big-integer arithmetic:

```
value in {1, -1, -2, 3}
product = value * 2^30                      (exact)
round   = 2^(shift-1) = 2^29
result  = (product + round) >> 30  =  value  (arithmetic shift)
```

## Minimal reproducer

```mlir
// f_const: both quantization parameters constant  -> correct
// f_dyn:   multiplier is a runtime tensor, shift is the constant 30 -> wrong
module {
  func.func @f_const(%in: tensor<4xi32>) -> tensor<4xi32> {
    %m = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32>
    %s = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8>
    %z = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32>
    %r = "tosa.rescale"(%in, %m, %s, %z, %z) <{input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = #tosa.rounding_mode<SINGLE_ROUND>, scale32 = true}> : (tensor<4xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<4xi32>
    func.return %r : tensor<4xi32>
  }
  func.func @f_dyn(%in: tensor<4xi32>, %m: tensor<1xi32>) -> tensor<4xi32> {
    %s = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8>
    %z = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32>
    %r = "tosa.rescale"(%in, %m, %s, %z, %z) <{input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = #tosa.rounding_mode<SINGLE_ROUND>, scale32 = true}> : (tensor<4xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<4xi32>
    func.return %r : tensor<4xi32>
  }
}
```

Independent reference (`apply_scale_32`, from the TOSA spec formula, computed with Python integers):

```python
def apply_scale_32(value, multiplier, shift):
    # Preconditions (TOSA 1.0.1): 2 <= shift <= 62, multiplier >= 0,
    # -2^(shift-1) <= value < 2^(shift-1). Under these the result always
    # fits in int32, so no saturation step is needed.
    acc = value * multiplier                 # exact 64-bit accumulator
    rnd = 1 << (shift - 1)
    return (acc + rnd) >> shift              # arithmetic shift
# multiplier = 2**30, shift = 30  ->  identity: [1,-1,-2,3] -> [1,-1,-2,3]
```

## Commands (verified end-to-end in a clean directory, exactly as shown)

Files: `min.mlir` = the reproducer above; `driver.ll` = an LLVM-IR driver that fills the input `[1, -1, -2, 3]`, calls `f_const`/`f_dyn` through the memref descriptor ABI, and prints the returned elements (it does not precompute expected values). The full driver source is inlined below, so this report is self-contained.

```bash
# toolchain: same-source rebuild of LLVM 67005b724c917e1bdca50c82ecaa1b21a69244ed (Release+assertions, macOS arm64)
# mlir-opt      4c65172e1a97c14b4ddb8c29a042a374398c2205ad2401470f421b77e2535c63
# mlir-translate 1f64073a7f78b5da8568d888ccabb57033fb5e5fd6695d05fe95ed9c79c17da0
# llvm-link     d65559097921ea51adfc17e132fd2b2a62f8d0efe6b1fe64c7df865251fe7f16
# llc           aa4b11550cbb8fa770fd9e4313f14199b4c71a25ec26062d1cb08514a9705679

# 1) lower (defect appears here)
mlir-opt min.mlir --mlir-disable-threading --verify-each   '--pass-pipeline=builtin.module(canonicalize,func.func(tosa-to-linalg),tosa-to-tensor,tosa-to-arith{include-apply-rescale=true},one-shot-bufferize{allow-return-allocs-from-loops=true bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map},convert-linalg-to-loops,convert-math-to-funcs,convert-math-to-llvm,expand-strided-metadata,lower-affine,convert-scf-to-cf,finalize-memref-to-llvm,convert-index-to-llvm,convert-arith-to-llvm,convert-cf-to-llvm,convert-func-to-llvm,reconcile-unrealized-casts)'   -o lowered.mlir

# 2) translate to LLVM IR
mlir-translate --mlir-to-llvmir lowered.mlir -o program.ll

# 3) link the driver, 4) generate code, 5) link executable, 6) run
llvm-link program.ll driver.ll -o linked.bc
llc -O2 -filetype=obj linked.bc -o program.o
clang program.o -o program
./program
```

`driver.ll` in full (self-contained; also archived):

```llvm
; Diagnostic derivative driver: prints returned size + 4 i32 elements.
declare { ptr, ptr, i64, [1 x i64], [1 x i64] } @f_const(ptr, ptr, i64, i64, i64)
declare { ptr, ptr, i64, [1 x i64], [1 x i64] } @f_dyn(ptr, ptr, i64, i64, i64, ptr, ptr, i64, i64, i64)
declare i32 @printf(ptr, ...)
@f1 = private unnamed_addr constant [13 x i8] c"f_const: %d:\00"
@f2 = private unnamed_addr constant [13 x i8] c"f_dyn:   %d:\00"
@fe = private unnamed_addr constant [5 x i8] c" %d\0A\00"
@in = global [4 x i32] [i32 1, i32 -1, i32 -2, i32 3]
@mul1 = global [1 x i32] [i32 1073741824]
define void @dump(ptr %tag, { ptr, ptr, i64, [1 x i64], [1 x i64] } %r) {
entry:
  %sz = extractvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %r, 3, 0
  %al = extractvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %r, 1
  %of = extractvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %r, 2
  %szf = trunc i64 %sz to i32
  call i32 (ptr,...) @printf(ptr %tag, i32 %szf)
  %base = getelementptr i32, ptr %al, i64 %of
  br label %loop
loop:
  %i = phi i64 [ 0, %entry ], [ %ni, %body ]
  %c = icmp slt i64 %i, 4
  br i1 %c, label %body, label %done
body:
  %p = getelementptr i32, ptr %base, i64 %i
  %v = load i32, ptr %p
  call i32 (ptr,...) @printf(ptr @fe, i32 %v)
  %ni = add i64 %i, 1
  br label %loop
done:
  ret void
}

define i32 @main() {
  %ip = getelementptr [4 x i32], ptr @in, i64 0, i64 0
  %mp = getelementptr [1 x i32], ptr @mul1, i64 0, i64 0
  %r1 = call { ptr, ptr, i64, [1 x i64], [1 x i64] } @f_const(ptr %ip, ptr %ip, i64 0, i64 4, i64 1)
  call void @dump(ptr @f1, { ptr, ptr, i64, [1 x i64], [1 x i64] } %r1)
  %r2 = call { ptr, ptr, i64, [1 x i64], [1 x i64] } @f_dyn(ptr %ip, ptr %ip, i64 0, i64 4, i64 1, ptr %mp, ptr %mp, i64 0, i64 1, i64 1)
  call void @dump(ptr @f2, { ptr, ptr, i64, [1 x i64], [1 x i64] } %r2)
  ret i32 0
}
```

Executed output in a clean directory (exit 0):

```
f_const: 4: 1
 -1
 -2
 3
f_dyn:   4: 1073741824
 0
 -1
 0
```

(`f_const` — both parameters constant — is correct. `f_dyn` — multiplier passed at runtime, shift constant 30 — is wrong: with an undefined shift value the result degenerates to the bare product, no shift and no rounding.)

## Expected behavior

`f_dyn` with `%m = 2^30` and `shift = 30` computes the identity: `[1, -1, -2, 3] -> [1, -1, -2, 3]` (and generally `(value*multiplier + (1<<(shift-1))) >> shift`).

## Actual behavior (executed, `llc -O2` + linked driver that reads the returned memref descriptor)

```
f_const: 4: 1 -1 -2 3          <- correct (both parameters constant)
f_dyn:   4: 1073741824 0 -1 0  <- wrong (constant shift 30 ignored; shift read from an empty tensor)
```

The symmetric configuration (constant multiplier, runtime shift) produces the same empty-`tensor<0xi32>` multiplier, and the `scale32 = false` (16-bit multiplier) variant produces the same empty `tensor<0xi8>` shift, so the defect is not specific to one side or one scale width.

## Impact

A `tosa.rescale` with EXT-DYNAMIC where exactly one of `multiplier`/`shift` is constant emits a zero-element constant tensor with an identity indexing map, and the `linalg.generic` body reads that parameter out of bounds (an undefined value; in our executed builds it behaved as 0, which drops the shift and the rounding and turns the rescale into a bare multiply). In the executed reproduction this silently produced wrong numeric results; two independent programs from a differential-testing pipeline showed 31/41 and 12/15 input frames differing from an independent reference with exactly that "missing shift" signature. Whether the out-of-bounds read yields 0 in every environment is not claimed.

## Suggested fix

Populate the constant lists whenever that **individual** operand is constant, e.g. fill `shiftValues` when `isShiftConstant` and `multiplierValues` when `isMultiplierConstant` (respecting `per_channel` semantics), so the helper never receives an empty value list for an operand it is told is constant. Alternatively, make `setupLinalgGenericOpInputAndIndexingMap` assert/fail when `isConstant && values.empty()`.

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

- [#157378](https://github.com/llvm/llvm-project/issues/157378) is the EXT-DYNAMIC tracking issue; it lists "RESCALE multiplier, shift, input_zp and output_zp" as **done** via PR #155967 — the very PR that introduced this mixed-case handling. This defect is **not** among the tracked items.
- PR #155967 "[mlir][tosa] Support RescaleOp with dynamic extension in TosaToLinalg" (merged 2025-10-14) is the introducing change.
- Targeted searches (`rescale dynamic multiplier constant shift`, `TosaToLinalg empty tensor shift`, `rescale wrong result dynamic extension`, `"tensor<0x"`) found no report of this mechanism. We could not find an existing report covering this specific failure mechanism as of 2026-11-03.
- Unrelated: #238030 (another SEMA-filed issue) concerns `convert-elementwise-to-linalg` and `arith.select`; different pass, different root cause.

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

Reply via email to