[Optimization] Compiler creates branches with allocs that can never be hit
- Dominant language
- F#
- Stars
- 4.3k
- Forks
- 876
- Avg merge
- 4d 11h
- Merged PRs (30d)
- 131
Description
Compiler creates branches with allocs that can never be hit, or it may create superfluous allocs that are never really used, the JIT will not be able to figure that out though.
https://sharplab.io/#v2:DYLgZgzgPsCmAuACAlgO2G2iC2BDADgPL7zID2qOB+sATomSeZQLyICwAUIj1fAMYALBkwqIA7snjCuvRFEQBlMtiwAPRAFoAfEpWwAFHnw16agJSzeCgHIUsOxHdSwuXOElzBsZCPACitLgQsAAmxKQUBuaILFY8HogAnojRsYgAzPEc3Lx4AsLKqgZJ0TFQusYRzKlgAK6UGo4aANSIAEwxktI5cgpF6lq6AKzZtvZDiAAs2e4IiA0u/LAQELi0SdVRMXG5CfMpaWxZe715uAV6xaXm5ZUEW5QG9Y2TrR1dUjKn/fqITbo1GMnBNHFMgA=
```fs
let inline mapOption mapper option =
match option with
| Some x -> Some(mapper x)
| None -> None
let almostErasedOption() =
let y () = 3
match Some(y()) |> mapOption (fun x -> x + 2) with
| Some x -> 5
| None -> 4
let unnecessaryOption() =
let y () = 3
match Some(y()) |> mapOption (fun x -> x + 2) with
| Some x -> x
| None -> 4
```
Decompiled:
```cs
public static int almostErasedOption()
{
if (FSharpOption.Some(5) == null)
{
return 4;
}
return 5;
}
public static int unnecessaryOption()
{
FSharpOption fSharpOption = FSharpOption.Some(5);
if (fSharpOption == null)
{
return 4;
}
return fSharpOption.Value;
}
```
The compiler is doing a pretty good job at constant folding but it really falls short by such a tiny margin to remove all the useless code.
These examples are contrived but in real cases cause inline code to not have the desired performance increase. Forcing people to write unidiomatic nullable reference returns or tricks with byref out vars.
Related:
https://github.com/athas/raytracers/pull/29
https://github.com/dotnet/coreclr/pull/21950#issuecomment-614822375
https://github.com/dotnet/fsharp/issues/8953
ValueOption is worse at inlining, especially without #8970
https://sharplab.io/#v2:DYLgZgzgPsCmAuACAlgO2G2iC2BDADgPL7zID2qOB+sATomSeZQLyICwAUIj1fAMYALBkwqIA7snjCuvRFEQA1XMACusAMplsWAB6IAtAD4lK9Vp0AKPPhr1dASlm8FytbAByFLMdPuvqLBcXHBIKthkEPAAorS4ELAAJsSkFJYOiCzOPKGIAJ6I6ZmIAMzZHNy8eALCbubasJZ56RlQJjYpzIVgqpT6vvoA1IgATBmS0hVyrmaaDYj9JgCs5TP+3oYmACzlIQiIvYH8sBAQuLR5nWkZWZU5+wVFbGV3U1W4NX71Vs0Ore0EK6USw9PqbBaIYZjCRSGSvNbfPTg3SrL6eDa+LZAA
Contributor guide
Assessment
This issue has not been assessed yet.