Conditionnally skip over Add/Sub/Or when used with a ternary and constant zero
#68.050 aperta il 2 mag 2023
Metriche repository
- Star
- (20.414 star)
- Metriche merge PR
- (Merge medio 6g 17h) (256 PR mergiate in 30 g)
Descrizione
When operations + - | (Add, Subtract, Bitwise-Or) are used with a ternary operator, in which one of the expression evaluates to a constant 0, I would expect the IL to just skip over that operation
(suggestion could be expanded to Multiply/Divide by ternary with constant 1, or Bitwise-And with ~0)
Version Used: sdk\7.0.203
Steps to Reproduce:
Here is my test code, with ChatInviteFlags being a [Flags] enum:
var ci = (ChatInviteFlags)int.Parse(Console.ReadLine());
int flags = 1024 |
(ci.HasFlag(ChatInviteFlags.broadcast) ? 32 : 0) |
(ci.HasFlag(ChatInviteFlags.pub) ? 64 : 0) |
(ci.HasFlag(ChatInviteFlags.megagroup) ? 128 : 0);
Console.WriteLine(flags);
Expected Behavior: I would expect the OR operations to be optimized by skipping over them entirely when the ternary conditions are false:
IL_0021: brfalse.s IL_0026
IL_0023: ldc.i4.s 32
IL_0025: or
Actual Behavior: Here is the IL currently generated:
IL_0021: brtrue.s IL_0026
IL_0023: ldc.i4.0
IL_0024: br.s IL_0028
IL_0026: ldc.i4.s 32
IL_0028: or