Repository navigation
Description
Description
The Mono WebAssembly interpreter produces incorrect results when a conditional expression supplies constant rotation counts directly to BitOperations.RotateLeft or RotateRight. The intrinsic transformation uses a constant emitted in a different basic block instead of the count selected at runtime.
Confirmed with browser runtime 10.0.14. The same assembly produces the expected results on desktop CoreCLR 10.0.14.
Reproduction Steps
Run the following code in a Release browser-wasm application using Mono interpretation with AOT disabled:
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
public static class Repro
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static ulong Rotate(ulong value, bool flag) => BitOperations.RotateLeft(value, flag ? 49 : 24);
public static void Main()
{
Console.WriteLine($"{Rotate(0x123456789ABCDEF0UL, false):X16}");
}
}Expected behavior
With flag set to false, rotate left by 24 bits:
789ABCDEF0123456
Actual behavior
The interpreter rotates left by 49 bits instead:
BDE02468ACF13579
Regression?
No response
Known Workarounds
Selecting the count into a local before the call works in the tested browser build:
[MethodImpl(MethodImplOptions.NoInlining)]
static ulong Rotate(ulong value, bool flag)
{
int count = flag ? 49 : 24;
return BitOperations.RotateLeft(value, count);
}Configuration
- Target: browser-wasm, Mono interpreter, single-threaded, AOT disabled.
- Runtime: 10.0.14
Other information
Building the test code, the Release IL correctly selects between the two counts:
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: brtrue.s IL_0008
IL_0004: ldc.i4.s 24
IL_0006: br.s IL_000a
IL_0008: ldc.i4.s 49
IL_000a: call uint64 System.Numerics.BitOperations::RotateLeft(uint64, int32)
IL_000f: ret
With MONO_VERBOSE_METHOD=Repro:Conditional, the join block already contains an immediate rotation in the unoptimized IR:
BB4:
IL_000a: rol.i8.imm [6 <- 2], 49
The rotation intrinsic handler in src/mono/mono/mini/interp/transform.c examines td->last_ins without checking that it belongs to td->cbb.
Proposed change: require the last emitted instruction to belong to the current basic block before specializing the rotation:
-if ((!strcmp (tm, "RotateLeft") || !strcmp (tm, "RotateRight")) && MINT_IS_LDC_I4 (td->last_ins->opcode)) {
+if ((!strcmp (tm, "RotateLeft") || !strcmp (tm, "RotateRight")) && td->last_ins == td->cbb->last_ins && MINT_IS_LDC_I4 (td->last_ins->opcode)) {Nearby conversion optimizations use the same guard.
Activity
dotnet-policy-service commentedon Nov 10, 2026
Tagging subscribers to this area: @vitek-karas, @BrzVlad, @kotlarmilos
See info in area-owners.md if you want to be subscribed.
Fix Mono rotation folding across basic blocks (dotnet#137284)