Summary
--tuple-optimization splits a tuple local into scalar locals and lowers local.set $t (tuple.make a0 a1) to $t0 = a0; $t1 = a1, in order. If an operand reads an element of $t that was already overwritten (a1 = tuple.extract 0 $t), it reads the new value:
t = (t.1, t.0) ==> $t0 = $t1; $t1 = $t0; // $t0 is already overwritten
The pass is in -O1 and above; a multivalue loop that swaps its parameters (plain wasm) is miscompiled by -O3, -Os, -Oz and -O4.
Evaluating the operands into temporaries first (as Heap2Local does for struct.new) would fix it.
Reproducer
test.wat:
(module
(func (export "f") (param $x i32) (param $y i32) (result i32)
(local $t (tuple i32 i32))
(local.set $t (tuple.make 2 (local.get $x) (local.get $y)))
(local.set $t (tuple.make 2 (tuple.extract 2 1 (local.get $t)) (tuple.extract 2 0 (local.get $t))))
(tuple.extract 2 1 (local.get $t))))
$ wasm-opt test.wat --enable-multivalue -o in.wasm
$ wasm-opt test.wat --enable-multivalue --tuple-optimization -o out.wasm
$ wasmtime run --invoke f in.wasm 16 1000
16
$ wasmtime run --invoke f out.wasm 16 1000
1000
f swaps the elements of t and returns t.1, which is the original x, so the correct result is 16. V8 gives the same results.
AI was used as part of the process of finding this issue. I have manually checked and reproduced it.
Summary
--tuple-optimizationsplits a tuple local into scalar locals and lowerslocal.set $t (tuple.make a0 a1)to$t0 = a0; $t1 = a1, in order. If an operand reads an element of$tthat was already overwritten (a1 = tuple.extract 0 $t), it reads the new value:The pass is in
-O1and above; a multivalueloopthat swaps its parameters (plain wasm) is miscompiled by-O3,-Os,-Ozand-O4.Evaluating the operands into temporaries first (as
Heap2Localdoes forstruct.new) would fix it.Reproducer
test.wat:fswaps the elements oftand returnst.1, which is the originalx, so the correct result is 16. V8 gives the same results.AI was used as part of the process of finding this issue. I have manually checked and reproduced it.