Skip to content

Optimizer: lower a state machine behind bindings left by an inlined Run - #20846

Open
auduchinok wants to merge 6 commits into
dotnet:mainfrom
auduchinok:optimize-stateMachineBindings
Open

auduchinok wants to merge 6 commits into
dotnet:mainfrom
auduchinok:optimize-stateMachineBindings

Conversation

@auduchinok

Copy link
Copy Markdown
Member

Fixes #20836.

@auduchinok
auduchinok requested a review from a team as a code owner October 22, 2026 14:07
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ Release notes checked


✅ Found changes and release notes in following paths:

Change path Release notes path Description
`src/Compiler` docs/release-notes/.FSharp.Compiler.Service/11.0.200.md

@T-Gro T-Gro left a comment

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.

🤖 🕵️ AI review — verify independently.

Comment thread src/Compiler/CodeGen/IlxGen.fs Outdated
let eenv = RemoveTemplateReplacement eenv
GenStructStateMachine cenv cgbuf eenv res sequel
let (LoweredStateMachine(prefixBindings = prefixBindings)) = res
GenStructStateMachineAfterPrefix cenv cgbuf eenv prefixBindings res sequel

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.

🤖 🕵️ [P1] Nested state-machine arguments read the wrong Data field — this prints 1 instead of 42 with --optimize+ and --optimize-; ILVerify fails with StackUnexpected. The prefix still needs the enclosing template replacement, which has already been removed here.

module IlPrefixProbe

#nowarn "3513"
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Core.CompilerServices.StateMachineHelpers

type Inner(offset: int) =
    member _.Offset = offset
    member inline this.Run(value: int) =
        if __useResumableCode then
            __stateMachine<unit, int>
                (MoveNextMethodImpl<_>(fun _ -> ()))
                (SetStateMachineMethodImpl<_>(fun _ _ -> ()))
                (AfterCode<_, _>(fun _ -> value + this.Offset))
        else
            value + this.Offset

let inline run () =
    if __useResumableCode then
        __stateMachine<int, int>
            (MoveNextMethodImpl<_>(fun _ -> ()))
            (SetStateMachineMethodImpl<_>(fun _ _ -> ()))
            (AfterCode<_, _>(fun sm ->
                sm.Data <- 41
                Inner(1).Run(sm.Data)))
    else
        42

[<EntryPoint>]
let main _ =
    let result = run ()
    printfn "%d" result
    if result = 42 then 0 else 1

@T-Gro T-Gro added the AI-reviewed PR reviewed by AI review council label Oct 23, 2026
@T-Gro
T-Gro self-requested a review October 23, 2026 07:48

@T-Gro T-Gro left a comment

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.

🤖 🕵️ Re-reviewed all recent changes as of 427970e; 1 finding

Comment thread src/Compiler/CodeGen/IlxGen.fs Outdated

and GenStructStateMachineAfterPrefix cenv cgbuf eenv prefixBindings res sequel =
match prefixBindings with
| [] -> GenStructStateMachine cenv cgbuf (RemoveTemplateReplacement eenv) res sequel

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.

🤖🕵️ [P1] Corrupted Data reads from an independent machine — this prints 1 instead of 42 with --optimize+ and --optimize-; the previous head prints 42.

#nowarn "3513"
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Core.CompilerServices.StateMachineHelpers

[<NoCompilerInlining>]
let sourceMachine () =
    let mutable sm = ResumableStateMachine<int>()
    sm.Data <- 41
    sm

type Inner(offset: int) =
    member _.Offset = offset
    member inline this.Run(value: int) =
        if __useResumableCode then
            __stateMachine<unit, int>
                (MoveNextMethodImpl<_>(fun _ -> ()))
                (SetStateMachineMethodImpl<_>(fun _ _ -> ()))
                (AfterCode<_, _>(fun _ -> value + this.Offset))
        else
            value + this.Offset

let inline run () =
    if __useResumableCode then
        __stateMachine<string, int>
            (MoveNextMethodImpl<_>(fun _ -> ()))
            (SetStateMachineMethodImpl<_>(fun _ _ -> ()))
            (AfterCode<_, _>(fun _ ->
                Inner(1).Run((sourceMachine ()).Data)))
    else
        42

[<EntryPoint>]
let main _ =
    let result = run ()
    printfn "%d" result
    if result = 42 then 0 else 1

@github-actions

Copy link
Copy Markdown
Contributor

Build Failure Analysis

Summary - The Windows Visual Studio build fails while compiling FSharp.Editor.Tests with repeated FS0331 errors in cancellable-task code that uses a type parameter constrained by both Roslyn's CodeFixProvider and the F# code-fix interfaces.

Root cause: state-machine lowering exposes ambiguous constrained receiver bindings

The failing compiler is the PR bootstrap compiler (artifacts/Bootstrap/fsc/FSharp.Build.dll). The VS binlog reports 31 errors from FSharp.Editor.Tests.fsproj; all source diagnostics reduce to two locations in unchanged code. The PR changes state-machine prefix binding selection/emission in LowerStateMachines.fs and IlxGen.fs, and the failures occur inside cancellableTask state machines using the constrained fixProvider receiver. This is consistent with the new prefix-binding path attempting to emit a generic receiver whose representation can resolve through two unrelated constraints.

Affected errors

Fix attempt - blocked

Delivery - none

No code was published. A source workaround could explicitly upcast the two receivers, but that would mask an optimizer/codegen regression outside the PR diff and was not published without targeted validation. The workspace has no usable .NET SDK, and this project is part of the Windows-only Visual Studio integration build.

Checks - binlog-mcp binlog_overview --binlog_file /data/binlogs/12_0_Windows_NT_WindowsCompressedMetadata_vs_release_Attempt1.binlog exited 0 and reported Build: FAILED, 80 projects, 31 errors, with FSharp.Editor.Tests.fsproj failing in CoreCompile. binlog_compiler identified the PR bootstrap FSharp.Build.dll as the Fsc assembly. dotnet build vsintegration/tests/FSharp.Editor.Tests/FSharp.Editor.Tests.fsproj -c Release --no-restore exited 155 because no .NET SDK is installed, so the original diagnostic and any candidate fix could not be validated locally. Several non-VS binlogs returned zero errors or successful overviews; some MCP queries timed out under the 32-leg batch, so no claim is made that every secondary leg was fully classified.

Build evidence

Structured data:

{
  "artifact_kind": "analysis",
  "fix_delivery": "none",
  "fix_status": "blocked",
  "workflow_artifact": "build-failure-analysis"
}

Automated content by GitHub Copilot. Generated by the Build Failure Analysis workflow. · copilot · gpt56 · 131.1 AIC · ⌖ 10.6 AIC · ⊞ 21.3K | [History]( · ◷)

@pcshrosbree pcshrosbree left a comment

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.

I have one evaluation-order question inline, and the second bot repro predates this PR. I built this PR's head (9389f24) and its merge base (fe180de) locally and ran both repros on them.

On the second bot finding (Data read from an independent machine): that repro prints 1 on both builds, with --optimize+ and with --optimize-, so it predates this PR. (SDK 10.0.402 prints 1 with --optimize+ and 42 with --optimize-.) While a template replacement is active, GenNamedTyAppAux swaps any ResumableStateMachine<_> for the template struct, whatever its type argument.

||> List.foldBack (fun bind (kept, needed) ->
let isKept =
Zset.contains bind.Var needed.FreeLocals
|| not (isExpandVar g bind.Var) && (not (isPureTemp g bind) || Zset.contains bind.Var used)

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.

This change makes an effect in the code argument run after the arguments that follow it. Should an effect in an expand-var definition stay in the prefix, or should such a machine take the dynamic path?

For example:

let inline mkCode () =
    note "make code" ()
    b.Delay(fun () -> b.Return 3)

b.Run(mkCode (), note "line arg" 7)

No kept binding needs code, so this drops it and keeps line. takeDefinition then expands code inside MoveNext, and TryReduceApp keeps note "make code" ahead of the body. With this PR's build, the repro below logs line arg, make code, body, with --optimize+ and with --optimize-. The source evaluation order is make code, line arg, body, and SDK 10.0.402's dynamic path (--optimize-) logs that order. The merge-base build logs make code, line arg, make code, body in both modes, so the PR replaces a duplicated effect with a reordered one.

Full repro
module Order
#nowarn "3513"
open System.Runtime.CompilerServices
open System.Runtime.InteropServices
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Core.CompilerServices.StateMachineHelpers

let log = ResizeArray<string>()

[<MethodImpl(MethodImplOptions.NoInlining)>]
let note (s: string) (v: 'a) = log.Add s; v

[<MethodImpl(MethodImplOptions.NoInlining)>]
let start<'M when 'M :> IAsyncStateMachine> (sm: byref<'M>) = sm.MoveNext()

[<Struct; NoEquality; NoComparison>]
type D<'T> = { mutable Result: 'T }

type B() =
    member inline _.Delay([<InlineIfLambda>] f: unit -> ResumableCode<'D, 'T>) =
        ResumableCode<'D, 'T>(fun sm -> (f ()).Invoke(&sm))

    member inline _.Return(v: 'T) =
        ResumableCode<D<'T>, 'T>(fun sm -> note "body" (); sm.Data.Result <- v; true)

    member inline _.Run(code: ResumableCode<D<'T>, 'T>, [<CallerLineNumber; Optional; DefaultParameterValue(0)>] line: int) : 'T =
        if __useResumableCode then
            __stateMachine<D<'T>, 'T>
                (MoveNextMethodImpl<D<'T>>(fun sm -> __resumeAt sm.ResumptionPoint; code.Invoke(&sm) |> ignore))
                (SetStateMachineMethodImpl<D<'T>>(fun _ _ -> ()))
                (AfterCode<D<'T>, 'T>(fun sm -> start &sm; note (sprintf "after line=%d" line) sm.Data.Result))
        else
            note "dynamic" ()
            let mutable sm = ResumableStateMachine<D<'T>>()
            code.Invoke(&sm) |> ignore
            note (sprintf "after line=%d" line) sm.Data.Result

let b = B()

let inline mkCode () =
    note "make code" ()
    b.Delay(fun () -> b.Return 3)

[<EntryPoint>]
let main _ =
    let r = b.Run(mkCode (), note "line arg" 7)
    printfn "%d: %s" r (String.concat ", " log)
    0

@T-Gro T-Gro left a comment

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.

🤖 🕵️ Re-reviewed all recent changes as of 9389f24; 1 finding

match e with
| Expr.Let (bind, bodyExpr, _, _) when isExpandVar g bind.Var || isUnusedPureTemp g bind bodyExpr ->
let env = if isExpandVar g bind.Var then recordDefinition env bind else env
Some (RewriteExpr (makeRewriteEnv env) bodyExpr)

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.

🤖 🕵️ [P2] Removing an address-taken expand-var local breaks optimized compilation: FS0971, Undefined value 'mutable copy'

#nowarn "3513"
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Core.CompilerServices.StateMachineHelpers

type Observer =
    [<NoCompilerInlining>]
    static member Touch<'T>(value: byref<'T>) : int = 42

let inline touchCopy (value: 'T) =
    let mutable copy = value
    Observer.Touch(&copy)

let inline run () =
    if __useResumableCode then
        __stateMachine<unit, int>
            (MoveNextMethodImpl<unit>(fun _ -> ()))
            (SetStateMachineMethodImpl<unit>(fun _ _ -> ()))
            (AfterCode<unit, int>(fun _ ->
                touchCopy (Unchecked.defaultof<ResumableCode<unit, unit>>)))
    else
        42

printfn "RESULT=%d" (run ())

@auduchinok
auduchinok force-pushed the optimize-stateMachineBindings branch from 1c15587 to 22c0e02 Compare November 10, 2026 14:39

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI-reviewed PR reviewed by AI review council

Projects

Status: New

3 participants